home *** CD-ROM | disk | FTP | other *** search
/ Software Vault: The Gold Collection / Software Vault - The Gold Collection (American Databankers) (1993).ISO / cdr55 / cfaq0593.zip / C.FAQ
Internet Message Format  |  1993-06-01  |  146KB

  1. From: scs@adam.mit.edu (Steve Summit)
  2. To:   Matthew.Hunt@p2.f3.n2616.z1.fidonet.org
  3. Date: Thu, 20 May 93 09:03:42 -0400
  4.  
  5. Here is the latest version of the comp.lang.c FAQ list.  You
  6. might also want to watch for newer versions in comp.lang.c, near
  7. the first of each month (see also the last question).
  8.  
  9. Newsgroups: comp.lang.c,comp.answers,news.answers
  10. From: scs@adam.mit.edu (Steve Summit)
  11. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  12. Message-ID: <1s387bINNrot@senator-bedfellow.MIT.EDU>
  13. Followup-To: poster
  14. Supersedes: <1pdstkINN3aj@senator-bedfellow.MIT.EDU>
  15. Reply-To: scs@adam.mit.edu
  16. X-Archive-Name: C-faq/faq
  17. Date: 3 May 1993 13:54:51 GMT
  18. X-Last-Modified: May 2, 1993
  19. Expires: 3 Jun 1993 00:00:00 GMT
  20. Lines: 3210
  21.  
  22. [Last modified May 2, 1993 by scs.]
  23.  
  24. Certain topics come up again and again on this newsgroup.  They are good
  25. questions, and the answers may not be immediately obvious, but each time
  26. they recur, much net bandwidth and reader time is wasted on repetitive
  27. responses, and on tedious corrections to the incorrect answers which are
  28. inevitably posted.
  29.  
  30. This article, which is posted monthly, attempts to answer these common
  31. questions definitively and succinctly, so that net discussion can move
  32. on to more constructive topics without continual regression to first
  33. principles.
  34.  
  35. No mere newsgroup article can substitute for thoughtful perusal of a
  36. full-length tutorial or language reference manual.  Anyone interested
  37. enough in C to be following this newsgroup should also be interested
  38. enough to read and study one or more such manuals, preferably several
  39. times.  Some vendors' compiler manuals are unfortunately inadequate; a
  40. few even perpetuate some of the myths which this article attempts to
  41. refute.  Several noteworthy books on C are listed in this article's
  42. bibliography.  Many of the questions and answers are cross-referenced to
  43. these books, for further study by the interested and dedicated reader
  44. (but beware of ANSI vs. ISO C Standard section numbers; see question
  45. 5.1).
  46.  
  47. If you have a question about C which is not answered in this article,
  48. first try to answer it by checking a few of the referenced books, or by
  49. asking knowledgeable colleagues, before posing your question to the net
  50. at large.  There are many people on the net who are happy to answer
  51. questions, but the volume of repetitive answers posted to one question,
  52. as well as the growing number of questions as the net attracts more
  53. readers, can become oppressive.  If you have questions or comments
  54. prompted by this article, please reply by mail rather than following up
  55. -- this article is meant to decrease net traffic, not increase it.
  56.  
  57. Besides listing frequently-asked questions, this article also summarizes
  58. frequently-posted answers.  Even if you know all the answers, it's worth
  59. skimming through this list once in a while, so that when you see one of
  60. its questions unwittingly posted, you won't have to waste time
  61. answering.
  62.  
  63. This article is always being improved.  Your input is welcomed.  Send
  64. your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or
  65. mit-eddie!adam.mit.edu!scs; this article's From: line may be unusable.
  66.  
  67. The questions answered here are divided into several categories:
  68.  
  69.          1. Null Pointers
  70.          2. Arrays and Pointers
  71.          3. Memory Allocation
  72.          4. Expressions
  73.          5. ANSI C
  74.          6. C Preprocessor
  75.          7. Variable-Length Argument Lists
  76.          8. Boolean Expressions and Variables
  77.          9. Structs, Enums, and Unions
  78.         10. Declarations
  79.         11. Stdio
  80.         12. Library Subroutines
  81.         13. Lint
  82.         14. Style
  83.         15. Floating Point
  84.         16. System Dependencies
  85.         17. Miscellaneous (Fortran to C converters, YACC grammars, etc.)
  86.  
  87. Herewith, some frequently-asked questions and their answers:
  88.  
  89.  
  90. Section 1. Null Pointers
  91.  
  92. 1.1:    What is this infamous null pointer, anyway?
  93.  
  94. A:      The language definition states that for each pointer type, there
  95.         is a special value -- the "null pointer" -- which is
  96.         distinguishable from all other pointer values and which is not
  97.         the address of any object.  That is, the address-of operator &
  98.         will never yield a null pointer, nor will a successful call to
  99.         malloc.  (malloc returns a null pointer when it fails, and this
  100.         is a typical use of null pointers: as a "special" pointer value
  101.         with some other meaning, usually "not allocated" or "not
  102.         pointing anywhere yet.")
  103.  
  104.         A null pointer is conceptually different from an uninitialized
  105.         pointer.  A null pointer is known not to point to any object; an
  106.         uninitialized pointer might point anywhere.  See also questions
  107.         3.1, 3.11, and 17.1.
  108.  
  109.         As mentioned in the definition above, there is a null pointer
  110.         for each pointer type, and the internal values of null pointers
  111.         for different types may be different.  Although programmers need
  112.         not know the internal values, the compiler must always be
  113.         informed which type of null pointer is required, so it can make
  114.         the distinction if necessary (see below).
  115.  
  116.         References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  117.         Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  118.  
  119. 1.2:    How do I "get" a null pointer in my programs?
  120.  
  121. A:      According to the language definition, a constant 0 in a pointer
  122.         context is converted into a null pointer at compile time.  That
  123.         is, in an initialization, assignment, or comparison when one
  124.         side is a variable or expression of pointer type, the compiler
  125.         can tell that a constant 0 on the other side requests a null
  126.         pointer, and generate the correctly-typed null pointer value.
  127.         Therefore, the following fragments are perfectly legal:
  128.  
  129.                 char *p = 0;
  130.                 if(p != 0)
  131.  
  132.         However, an argument being passed to a function is not
  133.         necessarily recognizable as a pointer context, and the compiler
  134.         may not be able to tell that an unadorned 0 "means" a null
  135.         pointer.  For instance, the Unix system call "execl" takes a
  136.         variable-length, null-pointer-terminated list of character
  137.         pointer arguments.  To generate a null pointer in a function
  138.         call context, an explicit cast is typically required, to force
  139.         the 0 to be in a pointer context:
  140.  
  141.                 execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  142.  
  143.         If the (char *) cast were omitted, the compiler would not know
  144.         to pass a null pointer, and would pass an integer 0 instead.
  145.         (Note that many Unix manuals get this example wrong.)
  146.  
  147.         When function prototypes are in scope, argument passing becomes
  148.         an "assignment context," and most casts may safely be omitted,
  149.         since the prototype tells the compiler that a pointer is
  150.         required, and of which type, enabling it to correctly convert
  151.         unadorned 0's.  Function prototypes cannot provide the types for
  152.         variable arguments in variable-length argument lists, however,
  153.         so explicit casts are still required for those arguments.  It is
  154.         safest always to cast null pointer function arguments, to guard
  155.         against varargs functions or those without prototypes, to allow
  156.         interim use of non-ANSI compilers, and to demonstrate that you
  157.         know what you are doing.  (Incidentally, it's also a simpler
  158.         rule to remember.)
  159.  
  160.         Summary:
  161.  
  162.                 Unadorned 0 okay:       Explicit cast required:
  163.  
  164.                 initialization          function call,
  165.                                         no prototype in scope
  166.                 assignment
  167.                                         variable argument in
  168.                 comparison              varargs function call
  169.  
  170.                 function call,
  171.                 prototype in scope,
  172.                 fixed argument
  173.  
  174.         References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
  175.         Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
  176.         Sec. 3.2.2.3 .
  177.  
  178. 1.3:    What is NULL and how is it #defined?
  179.  
  180. A:      As a matter of style, many people prefer not to have unadorned
  181.         0's scattered throughout their programs.  For this reason, the
  182.         preprocessor macro NULL is #defined (by <stdio.h> or
  183.         <stddef.h>), with value 0 (or (void *)0, about which more
  184.         later).  A programmer who wishes to make explicit the
  185.         distinction between 0 the integer and 0 the null pointer can
  186.         then use NULL whenever a null pointer is required.  This is a
  187.         stylistic convention only; the preprocessor turns NULL back to 0
  188.         which is then recognized by the compiler (in pointer contexts)
  189.         as before.  In particular, a cast may still be necessary before
  190.         NULL (as before 0) in a function call argument.  (The table
  191.         under question 1.2 above applies for NULL as well as 0.)
  192.  
  193.         NULL should _only_ be used for pointers; see question 1.8.
  194.  
  195.         References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  196.         Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  197.         Rationale Sec. 4.1.5 p. 74.
  198.  
  199. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  200.         bit pattern as the internal representation of a null pointer?
  201.  
  202. A:      Programmers should never need to know the internal
  203.         representation(s) of null pointers, because they are normally
  204.         taken care of by the compiler.  If a machine uses a nonzero bit
  205.         pattern for null pointers, it is the compiler's responsibility
  206.         to generate it when the programmer requests, by writing "0" or
  207.         "NULL," a null pointer.  Therefore, #defining NULL as 0 on a
  208.         machine for which internal null pointers are nonzero is as valid
  209.         as on any other, because the compiler must (and can) still
  210.         generate the machine's correct null pointers in response to
  211.         unadorned 0's seen in pointer contexts.
  212.  
  213. 1.5:    If NULL were defined as follows:
  214.  
  215.                 #define NULL (char *)0
  216.  
  217.         wouldn't that make function calls which pass an uncast NULL
  218.         work?
  219.  
  220. A:      Not in general.  The problem is that there are machines which
  221.         use different internal representations for pointers to different
  222.         types of data.  The suggested #definition would make uncast NULL
  223.         arguments to functions expecting pointers to characters to work
  224.         correctly, but pointer arguments to other types would still be
  225.         problematical, and legal constructions such as
  226.  
  227.                 FILE *fp = NULL;
  228.  
  229.         could fail.
  230.  
  231.         Nevertheless, ANSI C allows the alternate
  232.  
  233.                 #define NULL ((void *)0)
  234.  
  235.         definition for NULL.  Besides helping incorrect programs to work
  236.         (but only on machines with homogeneous pointers, thus
  237.         questionably valid assistance) this definition may catch
  238.         programs which use NULL incorrectly (e.g. when the ASCII  NUL
  239.         character was really intended; see question 1.8).
  240.  
  241.         References: ANSI Rationale Sec. 4.1.5 p. 74.
  242.  
  243. 1.6:    I use the preprocessor macro
  244.  
  245.                 #define Nullptr(type) (type *)0
  246.  
  247.         to help me build null pointers of the correct type.
  248.  
  249. A:      This trick, though popular in some circles, does not buy much.
  250.         It is not needed in assignments and comparisons; see question
  251.         1.2.  It does not even save keystrokes.  Its use suggests to the
  252.         reader that the author is shaky on the subject of null pointers,
  253.         and requires the reader to check the #definition of the macro,
  254.         its invocations, and _all_ other pointer usages much more
  255.         carefully.  See also question 8.1.
  256.  
  257. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  258.         null pointers valid?  What if the internal representation for
  259.         null pointers is nonzero?
  260.  
  261. A:      When C requires the boolean value of an expression (in the if,
  262.         while, for, and do statements, and with the &&, ||, !, and ?:
  263.         operators), a false value is produced when the expression
  264.         compares equal to zero, and a true value otherwise.  That is,
  265.         whenever one writes
  266.  
  267.                 if(expr)
  268.  
  269.         where "expr" is any expression at all, the compiler essentially
  270.         acts as if it had been written as
  271.  
  272.                 if(expr != 0)
  273.  
  274.         Substituting the trivial pointer expression "p" for "expr," we
  275.         have
  276.  
  277.                 if(p)   is equivalent to                if(p != 0)
  278.  
  279.         and this is a comparison context, so the compiler can tell that
  280.         the (implicit) 0 is a null pointer, and use the correct value.
  281.         There is no trickery involved here; compilers do work this way,
  282.         and generate identical code for both statements.  The internal
  283.         representation of a pointer does _not_ matter.
  284.  
  285.         The boolean negation operator, !, can be described as follows:
  286.  
  287.                 !expr   is essentially equivalent to    expr?0:1
  288.  
  289.         It is left as an exercise for the reader to show that
  290.  
  291.                 if(!p)  is equivalent to                if(p == 0)
  292.  
  293.         "Abbreviations" such as if(p), though perfectly legal, are
  294.         considered by some to be bad style.
  295.  
  296.         See also question 8.2.
  297.  
  298.         References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  299.         Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
  300.         3.6.5 .
  301.  
  302. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  303.  
  304. A:      Many programmers believe that "NULL" should be used in all
  305.         pointer contexts, as a reminder that the value is to be thought
  306.         of as a pointer.  Others feel that the confusion surrounding
  307.         "NULL" and "0" is only compounded by hiding "0" behind a
  308.         #definition, and prefer to use unadorned "0" instead.  There is
  309.         no one right answer.  C programmers must understand that "NULL"
  310.         and "0" are interchangeable and that an uncast "0" is perfectly
  311.         acceptable in initialization, assignment, and comparison
  312.         contexts.  Any usage of "NULL" (as opposed to "0") should be
  313.         considered a gentle reminder that a pointer is involved;
  314.         programmers should not depend on it (either for their own
  315.         understanding or the compiler's) for distinguishing pointer 0's
  316.         from integer 0's.
  317.  
  318.         NULL should _not_ be used when another kind of 0 is required,
  319.         even though it might work, because doing so sends the wrong
  320.         stylistic message.  (ANSI allows the #definition of NULL to be
  321.         (void *)0, which will not work in non-pointer contexts.)  In
  322.         particular, do not use NULL when the ASCII null character (NUL)
  323.         is desired.  Provide your own definition
  324.  
  325.                 #define NUL '\0'
  326.  
  327.         if you must.
  328.  
  329.         References: K&R II Sec. 5.4 p. 102.
  330.  
  331. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  332.         the value of NULL changes, perhaps on a machine with nonzero
  333.         null pointers?
  334.  
  335. A:      No.  Although symbolic constants are often used in place of
  336.         numbers because the numbers might change, this is _not_ the
  337.         reason that NULL is used in place of 0.  Once again, the
  338.         language guarantees that source-code 0's (in pointer contexts)
  339.         generate null pointers.  NULL is used only as a stylistic
  340.         convention.
  341.  
  342. 1.10:   I'm confused.  NULL is guaranteed to be 0, but the null pointer
  343.         is not?
  344.  
  345. A:      When the term "null" or "NULL" is casually used, one of several
  346.         things may be meant:
  347.  
  348.         1.      The conceptual null pointer, the abstract language
  349.                 concept defined in question 1.1.  It is implemented
  350.                 with...
  351.  
  352.         2.      The internal (or run-time) representation of a null
  353.                 pointer, which may or may not be all-bits-0 and which
  354.                 may be different for different pointer types.  The
  355.                 actual values should be of concern only to compiler
  356.                 writers.  Authors of C programs never see them, since
  357.                 they use...
  358.  
  359.         3.      The source code syntax for null pointers, which is the
  360.                 single character "0".  It is often hidden behind...
  361.  
  362.         4.      The NULL macro, which is #defined to be "0" or
  363.                 "(void *)0".  Finally, as red herrings, we have...
  364.  
  365.         5.      The ASCII null character (NUL), which does have all bits
  366.                 zero, but has no relation to the null pointer except in
  367.                 name; and...
  368.  
  369.         6.      The "null string," which is another name for an empty
  370.                 string ("").  The term "null string" can be confusing in
  371.                 C (and should perhaps be avoided), because it involves a
  372.                 null ('\0') character, but not a null pointer, which
  373.                 brings us full circle...
  374.  
  375.         This article always uses the phrase "null pointer" (in lower
  376.         case) for sense 1, the character "0" for sense 3, and the
  377.         capitalized word "NULL" for sense 4.
  378.  
  379. 1.11:   Why is there so much confusion surrounding null pointers?  Why
  380.         do these questions come up so often?
  381.  
  382. A:      C programmers traditionally like to know more than they need to
  383.         about the underlying machine implementation.  The fact that null
  384.         pointers are represented both in source code, and internally to
  385.         most machines, as zero invites unwarranted assumptions.  The use
  386.         of a preprocessor macro (NULL) suggests that the value might
  387.         change later, or on some weird machine.  The construct
  388.         "if(p == 0)" is easily misread as calling for conversion of p to
  389.         an integral type, rather than 0 to a pointer type, before the
  390.         comparison.  Finally, the distinction between the several uses
  391.         of the term "null" (listed above) is often overlooked.
  392.  
  393.         One good way to wade out of the confusion is to imagine that C
  394.         had a keyword (perhaps "nil", like Pascal) with which null
  395.         pointers were requested.  The compiler could either turn "nil"
  396.         into the correct type of null pointer, when it could determine
  397.         the type from the source code, or complain when it could not.
  398.         Now, in fact, in C the keyword for a null pointer is not "nil"
  399.         but "0", which works almost as well, except that an uncast "0"
  400.         in a non-pointer context generates an integer zero instead of an
  401.         error message, and if that uncast 0 was supposed to be a null
  402.         pointer, the code may not work.
  403.  
  404. 1.12:   I'm still confused.  I just can't understand all this null
  405.         pointer stuff.
  406.  
  407. A:      Follow these two simple rules:
  408.  
  409.         1.      When you want to refer to a null pointer in source code,
  410.                 use "0" or "NULL".
  411.  
  412.         2.      If the usage of "0" or "NULL" is an argument in a
  413.                 function call, cast it to the pointer type expected by
  414.                 the function being called.
  415.  
  416.         The rest of the discussion has to do with other people's
  417.         misunderstandings, or with the internal representation of null
  418.         pointers (which you shouldn't need to know), or with ANSI C
  419.         refinements.  Understand questions 1.1, 1.2, and 1.3, and
  420.         consider 1.8 and 1.11, and you'll do fine.
  421.  
  422. 1.13:   Given all the confusion surrounding null pointers, wouldn't it
  423.         be easier simply to require them to be represented internally by
  424.         zeroes?
  425.  
  426. A:      If for no other reason, doing so would be ill-advised because it
  427.         would unnecessarily constrain implementations which would
  428.         otherwise naturally represent null pointers by special, nonzero
  429.         bit patterns, particularly when those values would trigger
  430.         automatic hardware traps for invalid accesses.
  431.  
  432.         Besides, what would this requirement really accomplish?  Proper
  433.         understanding of null pointers does not require knowledge of the
  434.         internal representation, whether zero or nonzero.  Assuming that
  435.         null pointers are internally zero does not make any code easier
  436.         to write (except for a certain ill-advised usage of calloc; see
  437.         question 3.11).  Known-zero internal pointers would not obviate
  438.         casts in function calls, because the _size_ of the pointer might
  439.         still be different from that of an int.  (If "nil" were used to
  440.         request null pointers rather than "0," as mentioned in question
  441.         1.11, the urge to assume an internal zero representation would
  442.         not even arise.)
  443.  
  444. 1.14:   Seriously, have any actual machines really used nonzero null
  445.         pointers, or different representations for pointers to different
  446.         types?
  447.  
  448. A:      The Prime 50 series used segment 07777, offset 0 for the null
  449.         pointer, at least for PL/I.  Later models used segment 0, offset
  450.         0 for null pointers in C, necessitating new instructions such as
  451.         TCNP (Test C Null Pointer), evidently as a sop to all the extant
  452.         poorly-written C code which made incorrect assumptions.  Older,
  453.         word-addressed Prime machines were also notorious for requiring
  454.         larger byte pointers (char *'s) than word pointers (int *'s).
  455.  
  456.         The Eclipse MV series from Data General has three
  457.         architecturally supported pointer formats (word, byte, and bit
  458.         pointers), two of which are used by C compilers: byte pointers
  459.         for char * and void *, and word pointers for everything else.
  460.  
  461.         Some Honeywell-Bull mainframes use the bit pattern 06000 for
  462.         (internal) null pointers.
  463.  
  464.         The CDC Cyber 180 Series has 48-bit pointers consisting of a
  465.         ring, segment, and offset.  Most users (in ring 11) have null
  466.         pointers of 0xB00000000000.
  467.  
  468.         The Symbolics Lisp Machine, a tagged architecture, does not even
  469.         have conventional numeric pointers; it uses the pair <NIL, 0>
  470.         (basically a nonexistent <object, offset> handle) as a C null
  471.         pointer.
  472.  
  473.         Depending on the "memory model" in use, 80*86 processors (PC's)
  474.         may use 16 bit data pointers and 32 bit function pointers, or
  475.         vice versa.
  476.  
  477. 1.15:   What does a run-time "null pointer assignment" error mean?  How
  478.         do I track it down?
  479.  
  480. A:      This message, which occurs only under MS-DOS (see, therefore,
  481.         section 16) means that you've written, via a null pointer, to
  482.         location zero.
  483.  
  484.         A debugger will usually let you set a data breakpoint on
  485.         location 0.  Alternately, you could write a bit of code to copy
  486.         20 or so bytes from location 0 into another buffer, and
  487.         periodically check that it hasn't changed.
  488.  
  489.  
  490. Section 2. Arrays and Pointers
  491.  
  492. 2.1:    I had the definition char a[6] in one source file, and in
  493.         another I declared extern char *a.  Why didn't it work?
  494.  
  495. A:      The declaration extern char *a simply does not match the actual
  496.         definition.  The type "pointer-to-type-T" is not the same as
  497.         "array-of-type-T."  Use extern char a[].
  498.  
  499.         References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  500.  
  501. 2.2:    But I heard that char a[] was identical to char *a.
  502.  
  503. A:      Not at all.  (What you heard has to do with formal parameters to
  504.         functions; see question 2.4.)  Arrays are not pointers.  The
  505.         array declaration "char a[6];" requests that space for six
  506.         characters be set aside, to be known by the name "a."  That is,
  507.         there is a location named "a" at which six characters can sit.
  508.         The pointer declaration "char *p;" on the other hand, requests a
  509.         place which holds a pointer.  The pointer is to be known by the
  510.         name "p," and can point to any char (or contiguous array of
  511.         chars) anywhere.
  512.  
  513.         As usual, a picture is worth a thousand words.  The statements
  514.  
  515.                 char a[] = "hello";
  516.                 char *p = "world";
  517.  
  518.         would result in data structures which could be represented like
  519.         this:
  520.  
  521.                    +---+---+---+---+---+---+
  522.                 a: | h | e | l | l | o |\0 |
  523.                    +---+---+---+---+---+---+
  524.  
  525.                    +-----+     +---+---+---+---+---+---+
  526.                 p: |  *======> | w | o | r | l | d |\0 |
  527.                    +-----+     +---+---+---+---+---+---+
  528.  
  529.         It is important to realize that a reference like x[3] generates
  530.         different code depending on whether x is an array or a pointer.
  531.         Given the declarations above, when the compiler sees the
  532.         expression a[3], it emits code to start at the location "a,"
  533.         move three past it, and fetch the character there.  When it sees
  534.         the expression p[3], it emits code to start at the location "p,"
  535.         fetch the pointer value there, add three to the pointer, and
  536.         finally fetch the character pointed to.  In the example above,
  537.         both a[3] and p[3] happen to be the character 'l', but the
  538.         compiler gets there differently.  (See also question 17.14.)
  539.  
  540. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  541.         C?
  542.  
  543. A:      Much of the confusion surrounding pointers in C can be traced to
  544.         a misunderstanding of this statement.  Saying that arrays and
  545.         pointers are "equivalent" does not by any means imply that they
  546.         are interchangeable.
  547.  
  548.         "Equivalence" refers to the following key definition:
  549.  
  550.                 An lvalue [see question 2.5] of type array-of-T
  551.                 which appears in an expression decays (with
  552.                 three exceptions) into a pointer to its first
  553.                 element; the type of the resultant pointer is
  554.                 pointer-to-T.
  555.  
  556.         (The exceptions are when the array is the operand of a sizeof or
  557.         & operator, or is a literal string initializer for a character
  558.         array.)
  559.  
  560.         As a consequence of this definition, there is no apparent
  561.         difference in the behavior of the "array subscripting" operator
  562.         [] as it applies to arrays and pointers.  In an expression of
  563.         the form a[i], the array reference "a" decays into a pointer,
  564.         following the rule above, and is then subscripted just as would
  565.         be a pointer variable in the expression p[i] (although the
  566.         eventual memory accesses will be different, as explained in
  567.         question 2.2).  In either case, the expression x[i] (where x is
  568.         an array or a pointer) is, by definition, exactly equivalent to
  569.         *((x)+(i)).
  570.  
  571.         References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
  572.         Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .
  573.  
  574. 2.4:    Then why are array and pointer declarations interchangeable as
  575.         function formal parameters?
  576.  
  577. A:      Since arrays decay immediately into pointers, an array is never
  578.         actually passed to a function.  As a convenience, any parameter
  579.         declarations which "look like" arrays, e.g.
  580.  
  581.                 f(a)
  582.                 char a[];
  583.  
  584.         are treated by the compiler as if they were pointers, since that
  585.         is what the function will receive if an array is passed:
  586.  
  587.                 f(a)
  588.                 char *a;
  589.  
  590.         This conversion holds only within function formal parameter
  591.         declarations, nowhere else.  If this conversion bothers you,
  592.         avoid it; many people have concluded that the confusion it
  593.         causes outweighs the small advantage of having the declaration
  594.         "look like" the call and/or the uses within the function.
  595.  
  596.         References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
  597.         Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
  598.         Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
  599.         pp. 33-4.
  600.  
  601. 2.5:    How can an array be an lvalue, if you can't assign to it?
  602.  
  603. A:      The ANSI C Standard defines a "modifiable lvalue," which an
  604.         array is not.
  605.  
  606.         References: ANSI Sec. 3.2.2.1 p. 37.
  607.  
  608. 2.6:    Why doesn't sizeof properly report the size of an array which is
  609.         a parameter to a function?
  610.  
  611. A:      The sizeof operator reports the size of the pointer parameter
  612.         which the function actually receives (see question 2.4).
  613.  
  614. 2.7:    Someone explained to me that arrays were really just constant
  615.         pointers.
  616.  
  617. A:      This is a bit of an oversimplification.  An array name is
  618.         "constant" in that it cannot be assigned to, but an array is
  619.         _not_ a pointer, as the discussion and pictures in question 2.2
  620.         should make clear.
  621.  
  622. 2.8:    Practically speaking, what is the difference between arrays and
  623.         pointers?
  624.  
  625. A:      Arrays automatically allocate space, but can't be relocated or
  626.         resized.  Pointers must be explicitly assigned to point to
  627.         allocated space (perhaps using malloc), but can be reassigned
  628.         (i.e. pointed at different objects) at will, and have many other
  629.         uses besides serving as the base of blocks of memory.
  630.  
  631.         Due to the "equivalence of arrays and pointers" (see question
  632.         2.3), arrays and pointers often seem interchangeable, and in
  633.         particular a pointer to a block of memory assigned by malloc is
  634.         frequently treated (and can be referenced using [] exactly) as
  635.         if it were a true array (see also question 2.13).
  636.  
  637. 2.9:    I came across some "joke" code containing the "expression"
  638.         5["abcdef"] .  How can this be legal C?
  639.  
  640. A:      Yes, Virginia, array subscripting is commutative in C.  This
  641.         curious fact follows from the pointer definition of array
  642.         subscripting, namely that a[e] is exactly equivalent to
  643.         *((a)+(e)), for _any_ expression e and primary expression a, as
  644.         long as one of them is a pointer expression and one is integral.
  645.         This unsuspected commutativity is often mentioned in C texts as
  646.         if it were something to be proud of, but it finds no useful
  647.         application outside of the Obfuscated C Contest (see question
  648.         17.9).
  649.  
  650.         References: ANSI Rationale Sec. 3.3.2.1 p. 41.
  651.  
  652. 2.10:   My compiler complained when I passed a two-dimensional array to
  653.         a routine expecting a pointer to a pointer.
  654.  
  655. A:      The rule by which arrays decay into pointers is not applied
  656.         recursively.  An array of arrays (i.e. a two-dimensional array
  657.         in C) decays into a pointer to an array, not a pointer to a
  658.         pointer.  Pointers to arrays can be confusing, and must be
  659.         treated carefully.  (The confusion is heightened by the
  660.         existence of incorrect compilers, including some versions of pcc
  661.         and pcc-derived lint's, which improperly accept assignments of
  662.         multi-dimensional arrays to multi-level pointers.)  If you are
  663.         passing a two-dimensional array to a function:
  664.  
  665.                 int array[NROWS][NCOLUMNS];
  666.                 f(array);
  667.  
  668.         the function's declaration should match:
  669.  
  670.                 f(int a[][NCOLUMNS]) {...}
  671.         or
  672.                 f(int (*ap)[NCOLUMNS]) {...}    /* ap is a pointer to an array
  673. */
  674.  
  675.         In the first declaration, the compiler performs the usual
  676.         implicit parameter rewriting of "array of array" to "pointer to
  677.         array;" in the second form the pointer declaration is explicit.
  678.         Since the called function does not allocate space for the array,
  679.         it does not need to know the overall size, so the number of
  680.         "rows," NROWS, can be omitted.  The "shape" of the array is
  681.         still important, so the "column" dimension NCOLUMNS (and, for 3-
  682.         or more dimensional arrays, the intervening ones) must be
  683.         included.
  684.  
  685.         If a function is already declared as accepting a pointer to a
  686.         pointer, it is probably incorrect to pass a two-dimensional
  687.         array directly to it.
  688.  
  689.         References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.
  690.  
  691. 2.11:   How do I write functions which accept 2-dimensional arrays when
  692.         the "width" is not known at compile time?
  693.  
  694. A:      It's not easy.  One way is to pass in pointer to the [0][0]
  695.         element, along with the two dimensions, and simulate array
  696.         subscripting "by hand:"
  697.  
  698.                 f2(aryp, m, n)
  699.                 int *aryp;
  700.                 int m, n;
  701.                 { ... ary[i][j] is really aryp[i * n + j] ... }
  702.  
  703.         This function could be called with the array from question 2.10
  704.         as
  705.  
  706.                 f2(&array[0][0], NROWS, NCOLUMNS);
  707.  
  708.         See also question 2.14.
  709.  
  710. 2.12:   How do I declare a pointer to an array?
  711.  
  712. A:      Usually, you don't want to.  When people speak casually of a
  713.         pointer to an array, they usually mean a pointer to its first
  714.         element.
  715.  
  716.         Instead of a pointer to an array, consider using a pointer to
  717.         one of the array's elements instead.  Arrays of type T decay
  718.         into pointers to type T (see question 2.3), which is convenient;
  719.         subscripting or incrementing the resultant pointer accesses the
  720.         individual members of the array.  True pointers to arrays, when
  721.         subscripted or incremented, step over entire arrays, and are
  722.         generally only useful when operating on arrays of arrays, if at
  723.         all.  (See question 2.10 above.)
  724.  
  725.         If you really need to declare a pointer to an entire array, use
  726.         something like "int (*ap)[N];" where N is the size of the array.
  727.         (See also question 10.4.)  If the size of the array is unknown,
  728.         N can be omitted, but the resulting type, "pointer to array of
  729.         unknown size," is useless.
  730.  
  731. 2.13:   How can I dynamically allocate a multidimensional array?
  732.  
  733. A:      It is usually best to allocate an array of pointers, and then
  734.         initialize each pointer to a dynamically-allocated "row."  Here
  735.         is a two-dimensional example:
  736.  
  737.                 int **array1 = (int **)malloc(nrows * sizeof(int *));
  738.                 for(i = 0; i < nrows; i++)
  739.                         array1[i] = (int *)malloc(ncolumns * sizeof(int));
  740.  
  741.         (In "real" code, of course, malloc would be declared correctly,
  742.         and each return value checked.)
  743.  
  744.         You can keep the array's contents contiguous, while making later
  745.         reallocation of individual rows difficult, with a bit of
  746.         explicit pointer arithmetic:
  747.  
  748.                 int **array2 = (int **)malloc(nrows * sizeof(int *));
  749.                 array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  750.                 for(i = 1; i < nrows; i++)
  751.                         array2[i] = array2[0] + i * ncolumns;
  752.  
  753.         In either case, the elements of the dynamic array can be
  754.         accessed with normal-looking array subscripts: array[i][j].
  755.  
  756.         If the double indirection implied by the above schemes is for
  757.         some reason unacceptable, you can simulate a two-dimensional
  758.         array with a single, dynamically-allocated one-dimensional
  759.         array:
  760.  
  761.                 int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  762.  
  763.         However, you must now perform subscript calculations manually,
  764.         accessing the i,jth element with array3[i * ncolumns + j].  (A
  765.         macro can hide the explicit calculation, but invoking it then
  766.         requires parentheses and commas which don't look exactly like
  767.         multidimensional array subscripts.)
  768.  
  769.         Finally, you can use pointers-to-arrays:
  770.  
  771.                 int (*array4)[NCOLUMNS] =
  772.                         (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  773.  
  774.         , but the syntax gets horrific and all but one dimension must be
  775.         known at compile time.
  776.  
  777.         With all of these techniques, you may of course need to remember
  778.         to free the arrays (which may take several steps; see question
  779.         3.8) when they are no longer needed, and you cannot necessarily
  780.         intermix the dynamically-allocated arrays with conventional,
  781.         statically-allocated ones (see question 2.14 below, and also
  782.         question 2.10).
  783.  
  784. 2.14:   How can I use statically- and dynamically-allocated
  785.         multidimensional arrays interchangeably when passing them to
  786.         functions?
  787.  
  788. A:      There is no single perfect method.  Given the array and f() as
  789.         declared in question 2.10, f2() as declared in question 2.11,
  790.         array1, array2, array3, and array4 as declared in 2.13, and a
  791.         function f3() declared as:
  792.  
  793.                 f3(pp, m, n)
  794.                 int **pp;
  795.                 int m, n;
  796.  
  797.         ; the following calls would be legal, and work as expected:
  798.  
  799.                 f(array, NROWS, NCOLUMNS);
  800.                 f(array4, nrows, NCOLUMNS);
  801.                 f2(&array[0][0], NROWS, NCOLUMNS);
  802.                 f2(*array2, nrows, ncolumns);
  803.                 f2(array3, nrows, ncolumns);
  804.                 f2(*array4, nrows, NCOLUMNS);
  805.                 f3(array1, nrows, ncolumns);
  806.                 f3(array2, nrows, ncolumns);
  807.  
  808.         The following two calls would probably work, but involve
  809.         questionable casts, and work only if the dynamic ncolumns
  810.         matches the static NCOLUMNS:
  811.  
  812.                 f((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  813.                 f((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  814.  
  815.         If you can understand why all of the above calls work and are
  816.         written as they are, and if you understand why the combinations
  817.         that are not listed would not work, then you have a _very_ good
  818.         understanding of arrays and pointers (and several other areas)
  819.         in C.
  820.  
  821. 2.15:   Here's a neat trick: if I write
  822.  
  823.                 int realarray[10];
  824.                 int *array = &realarray[-1];
  825.  
  826.         I can treat "array" as if it were a 1-based array.
  827.  
  828. A:      Although this technique is attractive (and is used in the book
  829.         Numerical Recipes in C), it does not conform to the C standards.
  830.         Pointer arithmetic is defined only as long as the pointer points
  831.         within the same allocated block of memory, or to the imaginary
  832.         "terminating" element one past it; otherwise, the behavior is
  833.         undefined, _even if the pointer is not dereferenced_.  The code
  834.         above could fail if, while subtracting the offset, an illegal
  835.         address were generated (perhaps because the address tried to
  836.         "wrap around" past the beginning of some memory segment).
  837.  
  838.         References: ANSI Sec. 3.3.6 p. 48, Rationale Sec. 3.2.2.3 p. 38;
  839.         K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6.
  840.  
  841. 2.16:   I passed a pointer to a function which initialized it:
  842.  
  843.                 main()
  844.                 {
  845.                         int *ip;
  846.                         f(ip);
  847.                         return 0;
  848.                 }
  849.  
  850.                 void f(ip)
  851.                 int *ip;
  852.                 {
  853.                         static int dummy;
  854.                         ip = &dummy;
  855.                         *ip = 5;
  856.                 }
  857.  
  858.         , but the pointer in the caller was unchanged.
  859.  
  860. A:      Did the function try to initialize the pointer itself, or just
  861.         what it pointed to?  Remember that arguments in C are passed by
  862.         value.  The called function altered only the passed copy of the
  863.         pointer.  You'll want to pass the address of the pointer (the
  864.         function will end up accepting a pointer-to-a-pointer).
  865.  
  866. 2.17:   I have a char * pointer that happens to point to some ints, and
  867.         I want to step it over them.  Why doesn't
  868.  
  869.                 ((int *)p)++;
  870.  
  871.         work?
  872.  
  873. A:      In C, a cast operator does not mean "pretend these bits have a
  874.         different type, and treat them accordingly;" it is a conversion
  875.         operator, and by definition it yields an rvalue, which cannot be
  876.         assigned to, or incremented with ++.  (It is an anomaly in pcc-
  877.         derived compilers, and an extension in gcc, that expressions
  878.         such as the above are ever accepted.)  Say what you mean: use
  879.  
  880.                 p = (char *)((int *)p + 1);
  881.  
  882.         , or simply
  883.  
  884.                 p += sizeof(int);
  885.  
  886.         References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  887.  
  888.  
  889. Section 3. Memory Allocation
  890.  
  891. 3.1:    Why doesn't this fragment work?
  892.  
  893.                 char *answer;
  894.                 printf("Type something:\n");
  895.                 gets(answer);
  896.                 printf("You typed \"%s\"\n", answer);
  897.  
  898. A:      The pointer variable "answer," which is handed to the gets
  899.         function as the location into which the response should be
  900.         stored, has not been set to point to any valid storage.  That
  901.         is, we cannot say where the pointer "answer" points.  (Since
  902.         local variables are not initialized, and typically contain
  903.         garbage, it is not even guaranteed that "answer" starts out as a
  904.         null pointer.  See question 17.1.)
  905.  
  906.         The simplest way to correct the question-asking program is to
  907.         use a local array, instead of a pointer, and let the compiler
  908.         worry about allocation:
  909.  
  910.                 #include <string.h>
  911.  
  912.                 char answer[100], *p;
  913.                 printf("Type something:\n");
  914.                 fgets(answer, 100, stdin);
  915.                 if((p = strchr(answer, '\n')) != NULL)
  916.                         *p = '\0';
  917.                 printf("You typed \"%s\"\n", answer);
  918.  
  919.         Note that this example also uses fgets instead of gets (always a
  920.         good idea), so that the size of the array can be specified, so
  921.         that fgets will not overwrite the end of the array if the user
  922.         types an overly-long line.  (Unfortunately for this example,
  923.         fgets does not automatically delete the trailing \n, as gets
  924.         would.)  It would also be possible to use malloc to allocate the
  925.         answer buffer, and/or to parameterize its size
  926.         (#define ANSWERSIZE 100).
  927.  
  928. 3.2:    I can't get strcat to work.  I tried
  929.  
  930.                 char *s1 = "Hello, ";
  931.                 char *s2 = "world!";
  932.                 char *s3 = strcat(s1, s2);
  933.  
  934.         but I got strange results.
  935.  
  936. A:      Again, the problem is that space for the concatenated result is
  937.         not properly allocated.  C does not provide an automatically-
  938.         managed string type.  C compilers only allocate memory for
  939.         objects explicitly mentioned in the source code (in the case of
  940.         "strings," this includes character arrays and string literals).
  941.         The programmer must arrange (explicitly) for sufficient space
  942.         for the results of run-time operations such as string
  943.         concatenation, typically by declaring arrays, or by calling
  944.         malloc.
  945.  
  946.         strcat performs no allocation; the second string is appended to
  947.         the first one, in place.  Therefore, one fix would be to declare
  948.         the first string as an array with sufficient space:
  949.  
  950.                 char s1[20] = "Hello, ";
  951.  
  952.         Since strcat returns the value of its first argument (s1, in
  953.         this case), the s3 variable is superfluous.
  954.  
  955.         References: CT&P Sec. 3.2 p. 32.
  956.  
  957. 3.3:    But the man page for strcat says that it takes two char *'s as
  958.         arguments.  How am I supposed to know to allocate things?
  959.  
  960. A:      In general, when using pointers you _always_ have to consider
  961.         memory allocation, at least to make sure that the compiler is
  962.         doing it for you.  If a library routine's documentation does not
  963.         explicitly mention allocation, it is usually the caller's
  964.         problem.
  965.  
  966.         The Synopsis section at the top of a Unix-style man page can be
  967.         misleading.  The code fragments presented there are closer to
  968.         the function definition used by the call's implementor than the
  969.         invocation used by the caller.  In particular, many routines
  970.         which accept pointers (e.g. to structs or strings), are usually
  971.         called with the address of some object (a struct, or an array --
  972.         see questions 2.3 and 2.4.)  Another common example is stat().
  973.  
  974. 3.4:    I have a function that is supposed to return a string, but when
  975.         it returns to its caller, the returned string is garbage.
  976.  
  977. A:      Make sure that the memory to which the function returns a
  978.         pointer is correctly allocated.  The returned pointer should be
  979.         to a statically-allocated buffer, or to a buffer passed in by
  980.         the caller, but _not_ to a local array.  See also question 17.3.
  981.  
  982. 3.5:    You can't use dynamically-allocated memory after you free it,
  983.         can you?
  984.  
  985. A:      No.  Some early man pages for malloc stated that the contents of
  986.         freed memory was "left undisturbed;" this ill-advised guarantee
  987.         was never universal and is not required by ANSI.
  988.  
  989.         Few programmers would use the contents of freed memory
  990.         deliberately, but it is easy to do so accidentally.  Consider
  991.         the following (correct) code for freeing a singly-linked list:
  992.  
  993.                 struct list *listp, *nextp;
  994.                 for(listp = base; listp != NULL; listp = nextp) {
  995.                         nextp = listp->next;
  996.                         free((char *)listp);
  997.                 }
  998.  
  999.         and notice what would happen if the more-obvious loop iteration
  1000.         expression listp = listp->next were used, without the temporary
  1001.         nextp pointer.
  1002.  
  1003.         References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1004.         p. 95.
  1005.  
  1006. 3.6:    How does free() know how many bytes to free?
  1007.  
  1008. A:      The malloc/free package remembers the size of each block it
  1009.         allocates and returns, so it is not necessary to remind it of
  1010.         the size when freeing.
  1011.  
  1012. 3.7:    So can I query the malloc package to find out how big an
  1013.         allocated block is?
  1014.  
  1015. A:      Not portably.
  1016.  
  1017. 3.8:    I'm allocating structures which contain pointers to other
  1018.         dynamically-allocated objects.  When I free a structure, do I
  1019.         have to free each subsidiary pointer first?
  1020.  
  1021. A:      Yes.  In general, you must arrange that each pointer returned
  1022.         from malloc be individually passed to free, exactly once (if it
  1023.         is freed at all).
  1024.  
  1025. 3.9:    I have a program which mallocs but then frees a lot of memory,
  1026.         but memory usage (as reported by ps) doesn't seem to go back
  1027.         down.
  1028.  
  1029. A:      Most implementations of malloc/free do not return freed memory
  1030.         to the operating system (if there is one), but merely make it
  1031.         available for future malloc calls.
  1032.  
  1033. 3.10:   Is it legal to pass a null pointer as the first argument to
  1034.         realloc()?  Why would you want to?
  1035.  
  1036. A:      ANSI C sanctions this usage (and the related realloc(..., 0),
  1037.         which frees), but several earlier implementations do not support
  1038.         it, so it is not widely portable.  Passing an initially-null
  1039.         pointer to realloc can make it easier to write a self-starting
  1040.         incremental allocation algorithm.
  1041.  
  1042.         References: ANSI Sec. 4.10.3.4 .
  1043.  
  1044. 3.11:   What is the difference between calloc and malloc?  Is it safe to
  1045.         use calloc's zero-fill guarantee for pointer and floating-point
  1046.         values?  Does free work on memory allocated with calloc, or do
  1047.         you need a cfree?
  1048.  
  1049. A:      calloc(m, n) is essentially equivalent to
  1050.  
  1051.                 p = malloc(m * n);
  1052.                 memset(p, 0, m * n);
  1053.  
  1054.         The zero fill is all-bits-zero, and does not therefore guarantee
  1055.         useful zero values for pointers (see section 1 of this list) or
  1056.         floating-point values.  free can (and should) be used to free
  1057.         the memory allocated by calloc.
  1058.  
  1059.         References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  1060.  
  1061. 3.12:   What is alloca and why is its use discouraged?
  1062.  
  1063. A:      alloca allocates memory which is automatically freed when the
  1064.         function which called alloca returns.  That is, memory allocated
  1065.         with alloca is local to a particular function's "stack frame" or
  1066.         context.
  1067.  
  1068.         alloca cannot be written portably, and is difficult to implement
  1069.         on machines without a stack.  Its use is problematical (and the
  1070.         obvious implementation on a stack-based machine fails) when its
  1071.         return value is passed directly to another function, as in
  1072.         fgets(alloca(100), 100, stdin).
  1073.  
  1074.         For these reasons, alloca cannot be used in programs which must
  1075.         be widely portable, no matter how useful it might be.
  1076.  
  1077.         References: ANSI Rationale Sec. 4.10.3 p. 102.
  1078.  
  1079.  
  1080. Section 4. Expressions
  1081.  
  1082. 4.1:    Why doesn't this code:
  1083.  
  1084.                 a[i] = i++;
  1085.  
  1086.         work?
  1087.  
  1088. A:      The subexpression i++ causes a side effect -- it modifies i's
  1089.         value -- which leads to undefined behavior if i is also
  1090.         referenced elsewhere in the same expression.
  1091.  
  1092.         References: ANSI Sec. 3.3 p. 39.
  1093.  
  1094. 4.2:    Under my compiler, the code
  1095.  
  1096.                 int i = 7;
  1097.                 printf("%d\n", i++ * i++);
  1098.  
  1099.         prints 49.  Regardless of the order of evaluation, shouldn't it
  1100.         print 56?
  1101.  
  1102. A:      Although the postincrement and postdecrement operators ++ and --
  1103.         perform the operations after yielding the former value, the
  1104.         implication of "after" is often misunderstood.  It is _not_
  1105.         guaranteed that the operation is performed immediately after
  1106.         giving up the previous value and before any other part of the
  1107.         expression is evaluated.  It is merely guaranteed that the
  1108.         update will be performed sometime before the expression is
  1109.         considered "finished" (before the next "sequence point," in ANSI
  1110.         C's terminology).  In the example, the compiler chose to
  1111.         multiply the previous value by itself and to perform both
  1112.         increments afterwards.
  1113.  
  1114.         The behavior of code which contains multiple, ambiguous side
  1115.         effects has always been undefined.  Don't even try to find out
  1116.         how your compiler implements such things (contrary to the ill-
  1117.         advised exercises in many C textbooks); as K&R wisely point out,
  1118.         "if you don't know _how_ they are done on various machines, that
  1119.         innocence may help to protect you."
  1120.  
  1121.         References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  1122.         Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  1123.         (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  1124.  
  1125. 4.3:    But what about the &&, ||, and comma operators?
  1126.         I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  1127.  
  1128. A:      There is a special exception for those operators, (as well as
  1129.         ?: ); each of them does imply a sequence point (i.e. left-to-
  1130.         right evaluation is guaranteed).  Any book on C should make this
  1131.         clear.
  1132.  
  1133.         References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  1134.         K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  1135.         Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  1136.         CT&P Sec. 3.7 pp. 46-7.
  1137.  
  1138. 4.4:    If I'm not using the value of the expression, should I use i++
  1139.         or ++i to increment a variable?
  1140.  
  1141. A:      Since the two forms differ only in the value yielded, they are
  1142.         entirely equivalent when only their side effect is needed.  Some
  1143.         people will tell you that in the old days one form was preferred
  1144.         over the other because it utilized a PDP-11 autoincrement
  1145.         addressing mode, but those people are confused.
  1146.  
  1147. 4.5:    Why doesn't the code
  1148.  
  1149.                 int a = 1000, b = 1000;
  1150.                 long int c = a * b;
  1151.  
  1152.         work?
  1153.  
  1154. A:      Under C's integral promotion rules, the multiplication is
  1155.         carried out using int arithmetic, and the result may overflow
  1156.         and/or be truncated before being assigned to the long int left-
  1157.         hand-side.  Use an explicit cast to force long arithmetic:
  1158.  
  1159.                 long int c = (long int)a * b;
  1160.  
  1161.  
  1162. Section 5. ANSI C
  1163.  
  1164. 5.1:    What is the "ANSI C Standard?"
  1165.  
  1166. A:      In 1983, the American National Standards Institute commissioned
  1167.         a committee, X3J11, to standardize the C language.  After a
  1168.         long, arduous process, including several widespread public
  1169.         reviews, the committee's work was finally ratified as an
  1170.         American National Standard, X3.159-1989, on December 14, 1989,
  1171.         and published in the spring of 1990.  For the most part, ANSI C
  1172.         standardizes existing practice, with a few additions from C++
  1173.         (most notably function prototypes) and support for multinational
  1174.         character sets (including the much-lambasted trigraph
  1175.         sequences).  The ANSI C standard also formalizes the C run-time
  1176.         library support routines.
  1177.  
  1178.         The published Standard includes a "Rationale," which explains
  1179.         many of its decisions, and discusses a number of subtle points,
  1180.         including several of those covered here.  (The Rationale is "not
  1181.         part of ANSI Standard X3.159-1989, but is included for
  1182.         information only.")
  1183.  
  1184.         The Standard has been adopted as an international standard,
  1185.         ISO/IEC 9899:1990, although the sections are numbered
  1186.         differently (briefly, ANSI sections 2 through 4 correspond
  1187.         roughly to ISO sections 5 through 7), and the Rationale is
  1188.         currently not included.
  1189.  
  1190. 5.2:    How can I get a copy of the Standard?
  1191.  
  1192. A:      ANSI X3.159 has been officially superseded by ISO 9899.
  1193.         Copies are available from
  1194.  
  1195.                 American National Standards Institute
  1196.                 11 W. 42nd St., 13th floor
  1197.                 New York, NY  10036  USA
  1198.                 (+1) 212 642 4900
  1199.  
  1200.         or
  1201.  
  1202.                 Global Engineering Documents
  1203.                 2805 McGaw Avenue
  1204.                 Irvine, CA  92714  USA
  1205.                 (+1) 714 261 1455
  1206.                 (800) 854 7179  (U.S. & Canada)
  1207.  
  1208.         The cost is $130.00 from ANSI or $162.50 from Global.
  1209.         Copies of the original X3.159 (including the Rationale) are
  1210.         still available at $205.00 from ANSI or $200.50 from Global.
  1211.         (Editorial comment: yes, these prices are outrageous.)
  1212.  
  1213.         Note that ANSI derives revenues to support its operations from
  1214.         the sale of printed standards, so electronic copies are _not_
  1215.         available.
  1216.  
  1217.         The Rationale, by itself, has been printed by Silicon Press,
  1218.         ISBN 0-929306-07-4.
  1219.  
  1220. 5.3:    Does anyone have a tool for converting old-style C programs to
  1221.         ANSI C, or vice versa, or for automatically generating
  1222.         prototypes?
  1223.  
  1224. A:      First, are you sure you really need to convert lots of old code
  1225.         to ANSI C?  The old-style function syntax is still acceptable.
  1226.  
  1227.         Two programs, protoize and unprotoize, convert back and forth
  1228.         between prototyped and "old style" function definitions and
  1229.         declarations.  (These programs do _not_ handle full-blown
  1230.         translation between "Classic" C and ANSI C.)  These programs
  1231.         exist as patches to the FSF GNU C compiler, gcc.  Look for the
  1232.         file protoize-1.39.0.5.Z in pub/gnu at prep.ai.mit.edu
  1233.         (18.71.0.38), or at several other FSF archive sites.
  1234.  
  1235.         The unproto program (/pub/unix/unproto4.shar.Z on
  1236.         ftp.win.tue.nl) is a filter which sits between the preprocessor
  1237.         and the next compiler pass, converting most of ANSI C to
  1238.         traditional C on-the-fly.
  1239.  
  1240.         The GNU GhostScript package comes with a little program called
  1241.         ansi2knr.
  1242.  
  1243.         Several prototype generators exist, many as modifications to
  1244.         lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  1245.         March, 1992.  (See also question 17.8.)
  1246.  
  1247. 5.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  1248.         # to insert the value of a symbolic constant into a message, but
  1249.         it keeps stringizing the macro's name rather than its value.
  1250.  
  1251. A:      You must use something like the following two-step procedure to
  1252.         force the macro to be expanded as well as stringized:
  1253.  
  1254.                 #define str(x) #x
  1255.                 #define xstr(x) str(x)
  1256.                 #define OP plus
  1257.                 char *opname = xstr(OP);
  1258.  
  1259.         This sets opname to "plus" rather than "OP".
  1260.  
  1261.         An equivalent circumlocution is necessary with the token-pasting
  1262.         operator ## when the values (rather than the names) of two
  1263.         macros are to be concatenated.
  1264.  
  1265.         References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  1266.  
  1267. 5.5:    What's the difference between "char const *p" and
  1268.         "char * const p"?
  1269.  
  1270. A:      "char const *p" is a pointer to a constant character (you can't
  1271.         change the character); "char * const p" is a constant pointer to
  1272.         a (variable) character (i.e. you can't change the pointer).
  1273.         (Read these "inside out" to understand them.  See question
  1274.         10.4.)
  1275.  
  1276.         References: ANSI Sec. 3.5.4.1 .
  1277.  
  1278. 5.6:    Why can't I pass a char ** to a function which expects a
  1279.         const char **?
  1280.  
  1281. A:      You can use a pointer-to-T (for any type T) where a pointer-to-
  1282.         const-T is expected, but the rule (an explicit exception) which
  1283.         permits slight mismatches in qualified pointer types is not
  1284.         applied recursively, but only at the top level.
  1285.  
  1286.         You must use explicit casts (e.g. (const char **) in this case)
  1287.         when assigning (or passing) pointers which have qualifier
  1288.         mismatches at other than the first level of indirection.
  1289.  
  1290.         References: ANSI Sec. 3.1.2.6 p. 26, Sec. 3.3.16.1 p. 54,
  1291.         Sec. 3.5.3 p. 65.
  1292.  
  1293. 5.7:    My ANSI compiler complains about a mismatch when it sees
  1294.  
  1295.                 extern int func(float);
  1296.  
  1297.                 int func(x)
  1298.                 float x;
  1299.                 {...
  1300.  
  1301. A:      You have mixed the new-style prototype declaration
  1302.         "extern int func(float);" with the old-style definition
  1303.         "int func(x) float x;".  Old C (and ANSI C, in the absence of
  1304.         prototypes, and in variable-length argument lists) "widens"
  1305.         certain arguments when they are passed to functions.  Type float
  1306.         is promoted to double, and characters and short integers are
  1307.         promoted to integers.  (The values are automatically converted
  1308.         back to the corresponding narrower types within the body of the
  1309.         called function, if they are declared that way there.)
  1310.  
  1311.         The problem can be fixed either by using new-style syntax
  1312.         consistently in the definition:
  1313.  
  1314.                 int func(float x) { ... }
  1315.  
  1316.         or by changing the new-style prototype declaration to match the
  1317.         old-style definition:
  1318.  
  1319.                 extern int func(double);
  1320.  
  1321.         (In this case, it would be clearest to change the old-style
  1322.         definition to use double as well, as long as the address of that
  1323.         parameter is not taken.)
  1324.  
  1325.         It may also be safer to avoid "narrow" (char, short int, and
  1326.         float) function arguments and return types.
  1327.  
  1328.         References: ANSI Sec. 3.3.2.2 .
  1329.  
  1330. 5.8:    Why does the declaration
  1331.  
  1332.                 extern f(struct x {int s;} *p);
  1333.  
  1334.         give me an obscure warning message about "struct x introduced in
  1335.         prototype scope"?
  1336.  
  1337. A:      In a quirk of C's normal block scoping rules, a struct declared
  1338.         only within a prototype cannot be compatible with other structs
  1339.         declared in the same source file, nor can the struct tag be used
  1340.         later as you'd expect (it goes out of scope at the end of the
  1341.         prototype).
  1342.  
  1343.         To resolve the problem, precede the prototype with the vacuous-
  1344.         looking declaration
  1345.  
  1346.                 struct x;
  1347.  
  1348.         , which will reserve a place at file scope for struct x's
  1349.         definition, which will be completed by the struct declaration
  1350.         within the prototype.
  1351.  
  1352.         References: ANSI Sec. 3.1.2.1 p. 21, Sec. 3.1.2.6 p. 26,
  1353.         Sec. 3.5.2.3 p. 63.
  1354.  
  1355. 5.9:    I'm getting strange syntax errors inside code which I've
  1356.         #ifdeffed out.
  1357.  
  1358. A:      Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  1359.         #ifndef must still consist of "valid preprocessing tokens."
  1360.         This means that there must be no unterminated comments or quotes
  1361.         (note particularly that an apostrophe within a contracted word
  1362.         could look like the beginning of a character constant), and no
  1363.         newlines inside quotes.  Therefore, natural-language comments
  1364.         and pseudocode should always be written between the "official"
  1365.         comment delimiters /* and */.  (But see also question 17.10, and
  1366.         6.7.)
  1367.  
  1368.         References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  1369.  
  1370. 5.10:   Can I declare main as void, to shut off these annoying "main
  1371.         returns no value" messages?  (I'm calling exit(), so main
  1372.         doesn't return.)
  1373.  
  1374. A:      No.  main must be declared as returning an int, and as taking
  1375.         either zero or two arguments (of the appropriate type).  If
  1376.         you're calling exit() but still getting warnings, you'll have to
  1377.         insert a redundant return statement (or use some kind of
  1378.         "notreached" directive, if available).
  1379.  
  1380.         References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  1381.  
  1382. 5.11:   Is exit(status) truly equivalent to returning status from main?
  1383.  
  1384. A:      Yes, except under a few older, nonconforming systems.
  1385.  
  1386.         References: ANSI Sec. 2.1.2.2.3 p. 8.
  1387.  
  1388. 5.12:   Why does the ANSI Standard not guarantee more than six monocase
  1389.         characters of external identifier significance?
  1390.  
  1391. A:      The problem is older linkers which are neither under the control
  1392.         of the ANSI standard nor the C compiler developers on the
  1393.         systems which have them.  The limitation is only that
  1394.         identifiers be _significant_ in the first six characters, not
  1395.         that they be restricted to six characters in length.  This
  1396.         limitation is annoying, but certainly not unbearable, and is
  1397.         marked in the Standard as "obsolescent," i.e. a future revision
  1398.         will likely relax it.
  1399.  
  1400.         This concession to current, restrictive linkers really had to be
  1401.         made, no matter how vehemently some people oppose it.  (The
  1402.         Rationale notes that its retention was "most painful.")  If you
  1403.         disagree, or have thought of a trick by which a compiler
  1404.         burdened with a restrictive linker could present the C
  1405.         programmer with the appearance of more significance in external
  1406.         identifiers, read the excellently-worded section 3.1.2 in the
  1407.         X3.159 Rationale (see question 5.1), which discusses several
  1408.         such schemes and explains why they could not be mandated.
  1409.  
  1410.         References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  1411.         Sec. 3.1.2 pp. 19-21.
  1412.  
  1413. 5.13:   What is the difference between memcpy and memmove?
  1414.  
  1415. A:      memmove offers guaranteed behavior if the source and destination
  1416.         arguments overlap.  memcpy makes no such guarantee, and may
  1417.         therefore be more efficiently implementable.  When in doubt,
  1418.         it's safer to use memmove.
  1419.  
  1420.         References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  1421.         Sec. 4.11.2 .
  1422.  
  1423. 5.14:   My compiler is rejecting the simplest possible test programs,
  1424.         with all kinds of syntax errors.
  1425.  
  1426. A:      Perhaps it is a pre-ANSI compiler, unable to accept function
  1427.         prototypes and the like.
  1428.  
  1429. 5.15:   Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  1430.         compliant, accept this code?  I know that the code is ANSI,
  1431.         because gcc accepts it.
  1432.  
  1433. A:      Most compilers support a few non-Standard extensions, gcc more
  1434.         so than most.  Are you sure that the code being rejected doesn't
  1435.         rely on such an extension?  It is usually a bad idea to perform
  1436.         experiments with a particular compiler to determine properties
  1437.         of a language; the applicable standard may permit variations, or
  1438.         the compiler may be wrong.
  1439.  
  1440. 5.16:   Is char a[3] = "abc"; legal?  What does it mean?
  1441.  
  1442. A:      Yes, it is legal; it declares an array of size three,
  1443.         initialized with the three characters 'a', 'b', and 'c', without
  1444.         the usual terminating '\0' character.
  1445.  
  1446.         References: ANSI Sec. 3.5.7 pp. 72-3.
  1447.  
  1448. 5.17:   What are #pragmas and what are they good for?
  1449.  
  1450. A:      The #pragma directive provides a single, well-defined "escape
  1451.         hatch" which can be used for all sorts of implementation-
  1452.         specific controls and extensions: source listing control,
  1453.         structure packing, warning suppression (like the old lint
  1454.         /* NOTREACHED */ comments), etc.
  1455.  
  1456.         References: ANSI Sec. 3.8.6 .
  1457.  
  1458.  
  1459. Section 6. C Preprocessor
  1460.  
  1461. 6.1:    How can I write a generic macro to swap two values?
  1462.  
  1463. A:      There is no good answer to this question.  If the values are
  1464.         integers, a well-known trick using exclusive-OR could perhaps be
  1465.         used, but it will not work for floating-point values or
  1466.         pointers, or if the two values are the same variable, (and the
  1467.         "obvious" supercompressed implementation for integral types
  1468.         a^=b^=a^=b is in fact illegal due to multiple side-effects,
  1469.         and...).  If the macro is intended to be used on values of
  1470.         arbitrary type (the usual goal), it cannot use a temporary,
  1471.         since it does not know what type of temporary it needs, and
  1472.         standard C does not provide a typeof operator.
  1473.  
  1474.         The best all-around solution is probably to forget about using a
  1475.         macro, unless you're willing to pass in the type as a third
  1476.         argument.
  1477.  
  1478. 6.2:    I have some old code that tries to construct identifiers with a
  1479.         macro like
  1480.  
  1481.                 #define Paste(a, b) a/**/b
  1482.  
  1483.         but it doesn't work any more.
  1484.  
  1485. A:      That comments disappeared entirely and could therefore be used
  1486.         for token pasting was an undocumented feature of some early
  1487.         preprocessor implementations, notably Reiser's.  ANSI affirms
  1488.         (as did K&R) that comments are replaced with white space.
  1489.         However, since the need for pasting tokens was demonstrated and
  1490.         real, ANSI introduced a well-defined token-pasting operator, ##,
  1491.         which can be used like this:
  1492.  
  1493.                 #define Paste(a, b) a##b
  1494.  
  1495.         (See also question 5.4.)
  1496.  
  1497.         References: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  1498.  
  1499. 6.3:    What's the best way to write a multi-statement cpp macro?
  1500.  
  1501. A:      The usual goal is to write a macro that can be invoked as if it
  1502.         were a single function-call statement.  This means that the
  1503.         "caller" will be supplying the final semicolon, so the macro
  1504.         body should not.  The macro body cannot be a simple brace-
  1505.         delineated compound statement, because syntax errors would
  1506.         result if it were invoked (apparently as a single statement, but
  1507.         with a resultant extra semicolon) as the if branch of an if/else
  1508.         statement with an explicit else clause.
  1509.  
  1510.         The traditional solution is to use
  1511.  
  1512.                 #define Func() do { \
  1513.                         /* declarations */ \
  1514.                         stmt1; \
  1515.                         stmt2; \
  1516.                         /* ... */ \
  1517.                         } while(0)      /* (no trailing ; ) */
  1518.  
  1519.         When the "caller" appends a semicolon, this expansion becomes a
  1520.         single statement regardless of context.  (An optimizing compiler
  1521.         will remove any "dead" tests or branches on the constant
  1522.         condition 0, although lint may complain.)
  1523.  
  1524.         If all of the statements in the intended macro are simple
  1525.         expressions, with no declarations or loops, another technique is
  1526.         to write a single, parenthesized expression using one or more
  1527.         comma operators.  (See the example under question 6.10 below.
  1528.         This technique also allows a value to be "returned.")
  1529.  
  1530.         References: CT&P Sec. 6.3 pp. 82-3.
  1531.  
  1532. 6.4:    Is it acceptable for one header file to #include another?
  1533.  
  1534. A:      There has been considerable debate surrounding this question.
  1535.         Many people believe that "nested #include files" are to be
  1536.         avoided: the prestigious Indian Hill Style Guide (see question
  1537.         14.3) disparages them; they can make it harder to find relevant
  1538.         definitions; they can lead to multiple-declaration errors if a
  1539.         file is #included twice; and they make manual Makefile
  1540.         maintenance very difficult.  On the other hand, they make it
  1541.         possible to use header files in a modular way (a header file
  1542.         #includes what it needs itself, rather than requiring each
  1543.         #includer to do so, a requirement that can lead to intractable
  1544.         headaches); a tool like grep (or a tags file) makes it easy to
  1545.         find definitions no matter where they are; a popular trick:
  1546.  
  1547.                 #ifndef HEADER_FILE_NAME
  1548.                 #define HEADER_FILE_NAME
  1549.                 ...header file contents...
  1550.                 #endif
  1551.  
  1552.         makes a header file "idempotent" so that it can safely be
  1553.         #included multiple times; and automated Makefile maintenance
  1554.         tools (which are a virtual necessity in large projects anyway)
  1555.         handle dependency generation in the face of nested #include
  1556.         files easily.  See also section 14.
  1557.  
  1558. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  1559.  
  1560. A:      No.  Preprocessing happens during an earlier pass of
  1561.         compilation, before type names have been parsed.  Consider using
  1562.         the predefined constants in ANSI's <limits.h>, if applicable, or
  1563.         a "configure" script, instead.  (Better yet, try to write code
  1564.         which is inherently insensitive to type sizes.)
  1565.  
  1566.         References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  1567.         footnote 83.
  1568.  
  1569. 6.6:    How can I use a preprocessor #if expression to tell if a machine
  1570.         is big-endian or little-endian?
  1571.  
  1572. A:      You probably can't.  (Preprocessor arithmetic uses only long
  1573.         ints, and there is no concept of addressing.)  Are you sure you
  1574.         need to know the machine's endianness explicitly?  Usually it's
  1575.         better to write code which doesn't care.
  1576.  
  1577. 6.7:    I've got this tricky processing I want to do at compile time and
  1578.         I can't figure out a way to get cpp to do it.
  1579.  
  1580. A:      cpp is not intended as a general-purpose preprocessor.  Rather
  1581.         than forcing it to do something inappropriate, consider writing
  1582.         your own little special-purpose preprocessing tool, instead.
  1583.         You can easily get a utility like make(1) to run it for you
  1584.         automatically.
  1585.  
  1586.         If you are trying to preprocess something other than C, consider
  1587.         using a general-purpose preprocessor (such as m4).
  1588.  
  1589. 6.8:    I have some code which contains far too many #ifdef's for my
  1590.         taste.  How can I preprocess the code to leave only one
  1591.         conditional compilation set, without running it through cpp and
  1592.         expanding all of the #include's and #define's as well?
  1593.  
  1594. A:      There is a program floating around called unifdef which does
  1595.         exactly this.  (See question 17.8.)
  1596.  
  1597. 6.9:    How can I list all of the pre#defined identifiers?
  1598.  
  1599. A:      There's no standard way, although it is a frequent need.  The
  1600.         most expedient way is probably to extract printable strings from
  1601.         the compiler or preprocessor executable with something like the
  1602.         Unix strings(1) utility.
  1603.  
  1604. 6.10:   How can I write a cpp macro which takes a variable number of
  1605.         arguments?
  1606.  
  1607. A:      One popular trick is to define the macro with a single argument,
  1608.         and call it with a double set of parentheses, which appear to
  1609.         the preprocessor to indicate a single argument:
  1610.  
  1611.                 #define DEBUG(args) (printf("DEBUG: "), printf args)
  1612.  
  1613.                 if(n != 0) DEBUG(("n is %d\n", n));
  1614.  
  1615.         The obvious disadvantage is that the caller must always remember
  1616.         to use the extra parentheses.  Another solution is to use
  1617.         different macros (DEBUG1, DEBUG2, etc.) depending on the number
  1618.         of arguments.  (It is often better to use a bona-fide function,
  1619.         which can take a variable number of arguments in a well-defined
  1620.         way.  See questions 7.1 and 7.2 below.)
  1621.  
  1622.  
  1623. Section 7. Variable-Length Argument Lists
  1624.  
  1625. 7.1:    How can I write a function that takes a variable number of
  1626.         arguments?
  1627.  
  1628. A:      Use the <stdarg.h> header (or, if you must, the older
  1629.         <varargs.h>).
  1630.  
  1631.         Here is a function which concatenates an arbitrary number of
  1632.         strings into malloc'ed memory:
  1633.  
  1634.                 #include <stdlib.h>             /* for malloc, NULL, size_t */
  1635.                 #include <stdarg.h>             /* for va_ stuff */
  1636.                 #include <string.h>             /* for strcat et al */
  1637.  
  1638.                 char *vstrcat(char *first, ...)
  1639.                 {
  1640.                         size_t len = 0;
  1641.                         char *retbuf;
  1642.                         va_list argp;
  1643.                         char *p;
  1644.  
  1645.                         if(first == NULL)
  1646.                                 return NULL;
  1647.  
  1648.                         len = strlen(first);
  1649.  
  1650.                         va_start(argp, first);
  1651.  
  1652.                         while((p = va_arg(argp, char *)) != NULL)
  1653.                                 len += strlen(p);
  1654.  
  1655.                         va_end(argp);
  1656.  
  1657.                         retbuf = malloc(len + 1);       /* +1 for trailing \0 */
  1658.  
  1659.                         if(retbuf == NULL)
  1660.                                 return NULL;            /* error */
  1661.  
  1662.                         (void)strcpy(retbuf, first);
  1663.  
  1664.                         va_start(argp, first);
  1665.  
  1666.                         while((p = va_arg(argp, char *)) != NULL)
  1667.                                 (void)strcat(retbuf, p);
  1668.  
  1669.                         va_end(argp);
  1670.  
  1671.                         return retbuf;
  1672.                 }
  1673.  
  1674.         Usage is something like
  1675.  
  1676.                 char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  1677.  
  1678.         Note the cast on the last argument.  (Also note that the caller
  1679.         must free the returned, malloc'ed storage.)
  1680.  
  1681.         Under a pre-ANSI compiler, rewrite the function definition
  1682.         without a prototype ("char *vstrcat(first) char *first; {"),
  1683.         include <stdio.h> rather than <stdlib.h>, add "extern
  1684.         char *malloc();", and use int instead of size_t.  You may also
  1685.         have to delete the (void) casts, and use the older varargs
  1686.         package instead of stdarg.  See the next question for hints.
  1687.  
  1688.         Remember that in variable-length argument lists, function
  1689.         prototypes do not supply parameter type information; therefore,
  1690.         default argument promotions apply (see question 5.7), and null
  1691.         pointer arguments must be typed explicitly (see question 1.2).
  1692.  
  1693.         References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  1694.         Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  1695.  
  1696. 7.2:    How can I write a function that takes a format string and a
  1697.         variable number of arguments, like printf, and passes them to
  1698.         printf to do most of the work?
  1699.  
  1700. A:      Use vprintf, vfprintf, or vsprintf.
  1701.  
  1702.         Here is an "error" routine which prints an error message,
  1703.         preceded by the string "error: " and terminated with a newline:
  1704.  
  1705.                 #include <stdio.h>
  1706.                 #include <stdarg.h>
  1707.  
  1708.                 void
  1709.                 error(char *fmt, ...)
  1710.                 {
  1711.                         va_list argp;
  1712.                         fprintf(stderr, "error: ");
  1713.                         va_start(argp, fmt);
  1714.                         vfprintf(stderr, fmt, argp);
  1715.                         va_end(argp);
  1716.                         fprintf(stderr, "\n");
  1717.                 }
  1718.  
  1719.         To use the older <varargs.h> package, instead of <stdarg.h>,
  1720.         change the function header to:
  1721.  
  1722.                 void error(va_alist)
  1723.                 va_dcl
  1724.                 {
  1725.                         char *fmt;
  1726.  
  1727.         change the va_start line to
  1728.  
  1729.                 va_start(argp);
  1730.  
  1731.         and add the line
  1732.  
  1733.                 fmt = va_arg(argp, char *);
  1734.  
  1735.         between the calls to va_start and vfprintf.  (Note that there is
  1736.         no semicolon after va_dcl.)
  1737.  
  1738.         References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  1739.         Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  1740.  
  1741. 7.3:    How can I discover how many arguments a function was actually
  1742.         called with?
  1743.  
  1744. A:      This information is not available to a portable program.  Some
  1745.         systems provide a nonstandard nargs() function, but its use is
  1746.         questionable, since it typically returns the number of words
  1747.         passed, not the number of arguments.  (Floating point values and
  1748.         structures are usually passed as several words.)
  1749.  
  1750.         Any function which takes a variable number of arguments must be
  1751.         able to determine from the arguments themselves how many of them
  1752.         there are.  printf-like functions do this by looking for
  1753.         formatting specifiers (%d and the like) in the format string
  1754.         (which is why these functions fail badly if the format string
  1755.         does not match the argument list).  Another common technique
  1756.         (useful when the arguments are all of the same type) is to use a
  1757.         sentinel value (often 0, -1, or an appropriately-cast null
  1758.         pointer) at the end of the list (see the execl and vstrcat
  1759.         examples under questions 1.2 and 7.1 above).
  1760.  
  1761. 7.4:    I can't get the va_arg macro to pull in an argument of type
  1762.         pointer-to-function.
  1763.  
  1764. A:      The type-rewriting games which the va_arg macro typically plays
  1765.         are stymied by overly-complicated types such as pointer-to-
  1766.         function.  If you use a typedef for the function pointer type,
  1767.         however, all will be well.
  1768.  
  1769.         References: ANSI Sec. 4.8.1.2 p. 124.
  1770.  
  1771. 7.5:    How can I write a function which takes a variable number of
  1772.         arguments and passes them to some other function (which takes a
  1773.         variable number of arguments)?
  1774.  
  1775. A:      In general, you cannot.  You must provide a version of that
  1776.         other function which accepts a va_list pointer, as does vfprintf
  1777.         in the example above.  If the arguments must be passed directly
  1778.         as actual arguments (not indirectly through a va_list pointer)
  1779.         to another function which is itself variadic (for which you do
  1780.         not have the option of creating an alternate, va_list-accepting
  1781.         version) no portable solution is possible.  (The problem can be
  1782.         solved by resorting to machine-specific assembly language.)
  1783.  
  1784. 7.6:    How can I call a function with an argument list built up at run
  1785.         time?
  1786.  
  1787. A:      There is no guaranteed or portable way to do this.  If you're
  1788.         curious, ask this list's editor, who has a few wacky ideas you
  1789.         could try...  (See also question 16.10.)
  1790.  
  1791.  
  1792. Section 8. Boolean Expressions and Variables
  1793.  
  1794. 8.1:    What is the right type to use for boolean values in C?  Why
  1795.         isn't it a standard type?  Should #defines or enums be used for
  1796.         the true and false values?
  1797.  
  1798. A:      C does not provide a standard boolean type, because picking one
  1799.         involves a space/time tradeoff which is best decided by the
  1800.         programmer.  (Using an int for a boolean may be faster, while
  1801.         using char may save data space.)
  1802.  
  1803.         The choice between #defines and enums is arbitrary and not
  1804.         terribly interesting (see also question 9.1).  Use any of
  1805.  
  1806.                 #define TRUE  1                 #define YES 1
  1807.                 #define FALSE 0                 #define NO  0
  1808.  
  1809.                 enum bool {false, true};        enum bool {no, yes};
  1810.  
  1811.         or use raw 1 and 0, as long as you are consistent within one
  1812.         program or project.  (An enum may be preferable if your debugger
  1813.         expands enum values when examining variables.)
  1814.  
  1815.         Some people prefer variants like
  1816.  
  1817.                 #define TRUE (1==1)
  1818.                 #define FALSE (!TRUE)
  1819.  
  1820.         or define "helper" macros such as
  1821.  
  1822.                 #define Istrue(e) ((e) != 0)
  1823.  
  1824.         These don't buy anything (see question 8.2 below; see also
  1825.         question 1.6).
  1826.  
  1827. 8.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  1828.         is considered "true" in C?  What if a built-in boolean or
  1829.         relational operator "returns" something other than 1?
  1830.  
  1831. A:      It is true (sic) that any nonzero value is considered true in C,
  1832.         but this applies only "on input", i.e. where a boolean value is
  1833.         expected.  When a boolean value is generated by a built-in
  1834.         operator, it is guaranteed to be 1 or 0.  Therefore, the test
  1835.  
  1836.                 if((a == b) == TRUE)
  1837.  
  1838.         will work as expected (as long as TRUE is 1), but it is
  1839.         obviously silly.  In general, explicit tests against TRUE and
  1840.         FALSE are undesirable, because some library functions (notably
  1841.         isupper, isalpha, etc.) return, on success, a nonzero value
  1842.         which is _not_ necessarily 1.  (Besides, if you believe that
  1843.         "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  1844.         stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  1845.         good rule of thumb is to use TRUE and FALSE (or the like) only
  1846.         for assignment to a Boolean variable, or as the return value
  1847.         from a Boolean function, never in a comparison.
  1848.  
  1849.         The preprocessor macros TRUE and FALSE (and, of course, NULL)
  1850.         are used for code readability, not because the underlying values
  1851.         might ever change.  (See also question 1.7.)
  1852.  
  1853.         References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
  1854.         Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
  1855.         3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
  1856.         Tortoise.
  1857.  
  1858.  
  1859. Section 9. Structs, Enums, and Unions
  1860.  
  1861. 9.1:    What is the difference between an enum and a series of
  1862.         preprocessor #defines?
  1863.  
  1864. A:      At the present time, there is little difference.  Although many
  1865.         people might have wished otherwise, the ANSI standard says that
  1866.         enumerations may be freely intermixed with integral types,
  1867.         without errors.  (If such intermixing were disallowed without
  1868.         explicit casts, judicious use of enums could catch certain
  1869.         programming errors.)
  1870.  
  1871.         Some advantages of enums are that the numeric values are
  1872.         automatically assigned, that a debugger may be able to display
  1873.         the symbolic values when enum variables are examined, and that
  1874.         they obey block scope.  (A compiler may also generate nonfatal
  1875.         warnings when enums and ints are indiscriminately mixed, since
  1876.         doing so can still be considered bad style even though it is not
  1877.         strictly illegal).  A disadvantage is that the programmer has
  1878.         little control over the size (or over those nonfatal warnings).
  1879.  
  1880.         References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
  1881.         Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  1882.  
  1883. 9.2:    I heard that structures could be assigned to variables and
  1884.         passed to and from functions, but K&R I says not.
  1885.  
  1886. A:      What K&R I said was that the restrictions on struct operations
  1887.         would be lifted in a forthcoming version of the compiler, and in
  1888.         fact struct assignment and passing were fully functional in
  1889.         Ritchie's compiler even as K&R I was being published.  Although
  1890.         a few early C compilers lacked struct assignment, all modern
  1891.         compilers support it, and it is part of the ANSI C standard, so
  1892.         there should be no reluctance to use it.
  1893.  
  1894.         References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
  1895.         Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  1896.  
  1897. 9.3:    How does struct passing and returning work?
  1898.  
  1899. A:      When structures are passed as arguments to functions, the entire
  1900.         struct is typically pushed on the stack, using as many words as
  1901.         are required.  (Programmers often choose to use pointers to
  1902.         structures instead, precisely to avoid this overhead.)
  1903.  
  1904.         Structures are often returned from functions in a location
  1905.         pointed to by an extra, compiler-supplied "hidden" argument to
  1906.         the function.  Some older compilers used a special, static
  1907.         location for structure returns, although this made struct-valued
  1908.         functions nonreentrant, which ANSI C disallows.
  1909.  
  1910.         References: ANSI Sec. 2.2.3 p. 13.
  1911.  
  1912. 9.4:    The following program works correctly, but it dumps core after
  1913.         it finishes.  Why?
  1914.  
  1915.                 struct list
  1916.                         {
  1917.                         char *item;
  1918.                         struct list *next;
  1919.                         }
  1920.  
  1921.                 /* Here is the main program. */
  1922.  
  1923.                 main(argc, argv)
  1924.                 ...
  1925.  
  1926. A:      A missing semicolon causes the compiler to believe that main
  1927.         returns a structure.  (The connection is hard to see because of
  1928.         the intervening comment.)  Since struct-valued functions are
  1929.         usually implemented by adding a hidden return pointer, the
  1930.         generated code for main() tries to accept three arguments,
  1931.         although only two are passed (in this case, by the C start-up
  1932.         code).  See also question 17.15.
  1933.  
  1934.         References: CT&P Sec. 2.3 pp. 21-2.
  1935.  
  1936. 9.5:    Why can't you compare structs?
  1937.  
  1938. A:      There is no reasonable way for a compiler to implement struct
  1939.         comparison which is consistent with C's low-level flavor.  A
  1940.         byte-by-byte comparison could be invalidated by random bits
  1941.         present in unused "holes" in the structure (such padding is used
  1942.         to keep the alignment of later fields correct).  A field-by-
  1943.         field comparison would require unacceptable amounts of
  1944.         repetitive, in-line code for large structures.
  1945.  
  1946.         If you want to compare two structures, you must write your own
  1947.         function to do so.  C++ would let you arrange for the ==
  1948.         operator to map to your function.
  1949.  
  1950.         References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  1951.         Rationale Sec. 3.3.9 p. 47.
  1952.  
  1953. 9.6:    I came across some code that declared a structure like this:
  1954.  
  1955.                 struct name
  1956.                         {
  1957.                         int namelen;
  1958.                         char name[1];
  1959.                         };
  1960.  
  1961.         and then did some tricky allocation to make the name array act
  1962.         like it had several elements.  Is this legal and/or portable?
  1963.  
  1964. A:      This technique is popular, although Dennis Ritchie has called it
  1965.         "unwarranted chumminess with the compiler."  The ANSI C standard
  1966.         allows it only implicitly.  It seems to be portable to all known
  1967.         implementations.  (Compilers which check array bounds carefully
  1968.         might issue warnings.)
  1969.  
  1970.         References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.
  1971.  
  1972. 9.7:    How can I determine the byte offset of a field within a
  1973.         structure?
  1974.  
  1975. A:      ANSI C defines the offsetof macro, which should be used if
  1976.         available; see <stddef.h>.  If you don't have it, a suggested
  1977.         implementation is
  1978.  
  1979.                 #define offsetof(type, mem) ((size_t) \
  1980.                         ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  1981.  
  1982.         This implementation is not 100% portable; some compilers may
  1983.         legitimately refuse to accept it.
  1984.  
  1985.         See the next question for a usage hint.
  1986.  
  1987.         References: ANSI Sec. 4.1.5, Rationale Sec. 3.5.4.2 p. 55.
  1988.  
  1989. 9.8:    How can I access structure fields by name at run time?
  1990.  
  1991. A:      Build a table of names and offsets, using the offsetof() macro.
  1992.         The offset of field b in struct a is
  1993.  
  1994.                 offsetb = offsetof(struct a, b)
  1995.  
  1996.         If structp is a pointer to an instance of this structure, and b
  1997.         is an int field with offset as computed above, b's value can be
  1998.         set indirectly with
  1999.  
  2000.                 *(int *)((char *)structp + offsetb) = value;
  2001.  
  2002. 9.9:    Why does sizeof report a larger size than I expect for a
  2003.         structure type, as if there was padding at the end?
  2004.  
  2005. A:      Structures may have this padding (as well as internal padding;
  2006.         see also question 9.5), so that alignment properties will be
  2007.         preserved when an array of contiguous structures is allocated.
  2008.  
  2009. 9.10:   My compiler is leaving holes in structures, which is wasting
  2010.         space and preventing "binary" I/O to external data files.  Can I
  2011.         turn off the padding, or otherwise control the alignment of
  2012.         structs?
  2013.  
  2014. A:      Your compiler may provide an extension to give you this control
  2015.         (perhaps a #pragma), but there is no standard method.  See also
  2016.         question 17.2.
  2017.  
  2018. 9.11:   Can I initialize unions?
  2019.  
  2020. A:      ANSI Standard C allows an initializer for the first member of a
  2021.         union.  There is no standard way of initializing the other
  2022.         members (nor, under a pre-ANSI compiler, is there generally any
  2023.         way of initializing any of them).
  2024.  
  2025.  
  2026. Section 10. Declarations
  2027.  
  2028. 10.1:   How do you decide which integer type to use?
  2029.  
  2030. A:      If you might need large values (above 32767 or below -32767),
  2031.         use long.  Otherwise, if space is very important (there are
  2032.         large arrays or many structures), use short.  Otherwise, use
  2033.         int.  If well-defined overflow characteristics are important
  2034.         and/or negative values are not, use the corresponding unsigned
  2035.         types.  (But beware of mixing signed and unsigned in
  2036.         expressions.)  Similar arguments apply when deciding between
  2037.         float and double.
  2038.  
  2039.         Although char or unsigned char can be used as a "tiny" int type,
  2040.         doing so is often more trouble than it's worth, due to
  2041.         unpredictable sign extension and increased code size.
  2042.  
  2043.         These rules obviously don't apply if the address of a variable
  2044.         is taken and must have a particular type.
  2045.  
  2046.         If for some reason you need to declare something with an _exact_
  2047.         size (usually the only good reason for doing so is when
  2048.         attempting to conform to some externally-imposed storage layout,
  2049.         but see question 17.2), be sure to encapsulate the choice behind
  2050.         an appropriate typedef.
  2051.  
  2052. 10.2:   What should the 64-bit type on new, 64-bit machines be?
  2053.  
  2054. A:      Some vendors of C products for 64-bit machines support 64-bit
  2055.         long ints.  Others fear that too much existing code depends on
  2056.         sizeof(int) == sizeof(long) == 32 bits, and introduce a new 64-
  2057.         bit long long int type instead.
  2058.  
  2059.         Programmers interested in writing portable code should therefore
  2060.         insulate their 64-bit type needs behind appropriate typedefs.
  2061.         Vendors who feel compelled to introduce a new long long int type
  2062.         should advertise it as being "at least 64 bits" (which is truly
  2063.         new; a type traditional C doesn't have), and not "exactly 64
  2064.         bits."
  2065.  
  2066. 10.3:   I can't seem to define a linked list successfully.  I tried
  2067.  
  2068.                 typedef struct
  2069.                         {
  2070.                         char *item;
  2071.                         NODEPTR next;
  2072.                         } *NODEPTR;
  2073.  
  2074.         but the compiler gave me error messages.  Can't a struct in C
  2075.         contain a pointer to itself?
  2076.  
  2077. A:      Structs in C can certainly contain pointers to themselves; the
  2078.         discussion and example in section 6.5 of K&R make this clear.
  2079.         The problem with this example is that the NODEPTR typedef is not
  2080.         complete at the point where the "next" field is declared.  To
  2081.         fix it, first give the structure a tag ("struct node").  Then,
  2082.         declare the "next" field as "struct node *next;", and/or move
  2083.         the typedef declaration wholly before or wholly after the struct
  2084.         declaration.  One corrected version would be
  2085.  
  2086.                 struct node
  2087.                         {
  2088.                         char *item;
  2089.                         struct node *next;
  2090.                         };
  2091.  
  2092.                 typedef struct node *NODEPTR;
  2093.  
  2094.         , and there are at least three other equivalently correct ways
  2095.         of arranging it.
  2096.  
  2097.         A similar problem, with a similar solution, can arise when
  2098.         attempting to declare a pair of typedef'ed mutually recursive
  2099.         structures.
  2100.  
  2101.         References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S
  2102.         Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  2103.  
  2104. 10.4:   How do I declare an array of pointers to functions returning
  2105.         pointers to functions returning pointers to characters?
  2106.  
  2107. A:      This question can be answered in at least three ways (all
  2108.         declare the hypothetical array with 5 elements):
  2109.  
  2110.         1.  char *(*(*a[5])())();
  2111.  
  2112.         2.  Build the declaration up in stages, using typedefs:
  2113.  
  2114.                 typedef char *pc;       /* pointer to char */
  2115.                 typedef pc fpc();       /* function returning pointer to char */
  2116.                 typedef fpc *pfpc;      /* pointer to above */
  2117.                 typedef pfpc fpfpc();   /* function returning... */
  2118.                 typedef fpfpc *pfpfpc;  /* pointer to... */
  2119.                 pfpfpc a[5];            /* array of... */
  2120.  
  2121.         3.  Use the cdecl program, which turns English into C and vice
  2122.             versa:
  2123.  
  2124.                 cdecl> declare a as array 5 of pointer to function returning
  2125.                          pointer to function returning pointer to char
  2126.                 char *(*(*a[5])())()
  2127.  
  2128.             cdecl can also explain complicated declarations, help with
  2129.             casts, and indicate which set of parentheses the arguments
  2130.             go in (for complicated function definitions, like the
  2131.             above).  Versions of cdecl are in volume 14 of
  2132.             comp.sources.unix (see question 17.8) and K&R II.
  2133.  
  2134.         Any good book on C should explain how to read these complicated
  2135.         C declarations "inside out" to understand them ("declaration
  2136.         mimics use").
  2137.  
  2138.         References: K&R II Sec. 5.12 p. 122; H&S Sec. 5.10.1 p. 116.
  2139.  
  2140. 10.5:   I'm building a state machine with a bunch of functions, one for
  2141.         each state.  I want to implement state transitions by having
  2142.         each function return a pointer to the next state function.  I
  2143.         find a limitation in C's declaration mechanism: there's no way
  2144.         to declare these functions as returning a pointer to a function
  2145.         returning a pointer to a function returning a pointer to a
  2146.         function...
  2147.  
  2148. A:      You can't do it directly.  Either have the function return a
  2149.         generic function pointer type, and apply a cast before calling
  2150.         through it; or have it return a structure containing only a
  2151.         pointer to a function returning that structure.
  2152.  
  2153. 10.6:   What's the best way to declare and define global variables?
  2154.  
  2155. A:      First, though there can be many _declarations_ (and in many
  2156.         translation units) of a single "global" (strictly speaking,
  2157.         "external") variable (or function), there must be exactly one
  2158.         _definition_.  (The definition is the declaration that actually
  2159.         allocates space, and provides an initialization value, if any.)
  2160.         It is best to place the definition in some central (to the
  2161.         program, or to the module) .c file, with an external declaration
  2162.         in a header (".h") file, which is #included wherever the
  2163.         declaration is needed.  The .c file containing the definition
  2164.         should also #include the header file containing the external
  2165.         declaration, so that the compiler can check that the
  2166.         declarations match.
  2167.  
  2168.         This rule promotes a high degree of portability, and is
  2169.         consistent with the requirements of the ANSI C Standard.  Note
  2170.         that Unix compilers and linkers typically use a "common model"
  2171.         which allows multiple (uninitialized) definitions.  A few very
  2172.         odd systems may require an explicit initializer to distinguish a
  2173.         definition from an external declaration.
  2174.  
  2175.         It is possible to use preprocessor tricks to arrange that the
  2176.         declaration need only be typed once, in the header file, and
  2177.         "turned into" a definition, during exactly one #inclusion, via a
  2178.         special #define.
  2179.  
  2180.         References: K&R I Sec. 4.5 pp. 76-7; K&R II Sec. 4.4 pp. 80-1;
  2181.         ANSI Sec. 3.1.2.2 (esp. Rationale), Secs. 3.7, 3.7.2,
  2182.         Sec. F.5.11 .
  2183.  
  2184. 10.7:   I finally figured out the syntax for declaring pointers to
  2185.         functions, but now how do I initialize one?
  2186.  
  2187. A:      Use something like
  2188.  
  2189.                 extern int func();
  2190.                 int (*fp)() = func;
  2191.  
  2192.         When the name of a function appears in an expression but is not
  2193.         being called (i.e. is not followed by a "("), it "decays" into a
  2194.         pointer (i.e. it has its address implicitly taken), much as an
  2195.         array name does.
  2196.  
  2197.         An explicit extern declaration for the function is normally
  2198.         needed, since implicit external function declaration does not
  2199.         happen in this case (again, because the function name is not
  2200.         followed by a "(").
  2201.  
  2202. 10.8:   I've seen different methods used for calling through pointers to
  2203.         functions.  What's the story?
  2204.  
  2205. A:      Originally, a pointer to a function had to be "turned into" a
  2206.         "real" function, with the * operator (and an extra pair of
  2207.         parentheses, to keep the precedence straight), before calling:
  2208.  
  2209.                 int r, func(), (*fp)() = func;
  2210.                 r = (*fp)();
  2211.  
  2212.         It can also be argued that functions are always called through
  2213.         pointers, but that "real" functions decay implicitly into
  2214.         pointers (in expressions, as they do in initializations) and so
  2215.         cause no trouble.  This reasoning, made widespread through pcc
  2216.         and adopted in the ANSI standard, means that
  2217.  
  2218.                 r = fp();
  2219.  
  2220.         is legal and works correctly, whether fp is a function or a
  2221.         pointer to one.  (The usage has always been unambiguous; there
  2222.         is nothing you ever could have done with a function pointer
  2223.         followed by an argument list except call through it.)  An
  2224.         explicit * is harmless, and still allowed (and recommended, if
  2225.         portability to older compilers is important).
  2226.  
  2227.         References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41.
  2228.  
  2229.  
  2230. Section 11. Stdio
  2231.  
  2232. 11.1:   Why doesn't this code:
  2233.  
  2234.                 char c;
  2235.                 while((c = getchar()) != EOF)...
  2236.  
  2237.         work?
  2238.  
  2239. A:      For one thing, the variable to hold getchar's return value must
  2240.         be an int.  getchar can return all possible character values, as
  2241.         well as EOF.  By passing getchar's return value through a char,
  2242.         either a normal character might be misinterpreted as EOF, or the
  2243.         EOF might be altered and so never seen.
  2244.  
  2245.         References: CT&P Sec. 5.1 p. 70.
  2246.  
  2247. 11.2:   Why doesn't the code scanf("%d", i); work?
  2248.  
  2249. A:      You must always pass addresses (in this case, &i) to scanf.
  2250.  
  2251. 11.3:   Why doesn't this code:
  2252.  
  2253.                 double d;
  2254.                 scanf("%f", &d);
  2255.  
  2256.         work?
  2257.  
  2258. A:      With scanf, use %lf for values of type double, and %f for float.
  2259.         (Note the discrepancy with printf, which uses %f for both double
  2260.         and float, due to C's default argument promotion rules.)
  2261.  
  2262. 11.4:   Why won't the code
  2263.  
  2264.                 while(!feof(fp))
  2265.                         fgets(buf, MAXLINE, fp);
  2266.  
  2267.         work?
  2268.  
  2269. A:      C's I/O is not like Pascal's.  EOF is only indicated _after_ an
  2270.         input routine has tried to read, and has reached end-of-file.
  2271.         Usually, you should just check the return value of the input
  2272.         routine (fgets in this case); feof() is rarely needed.
  2273.  
  2274. 11.5:   Why does everyone say not to use gets()?
  2275.  
  2276. A:      It cannot be told the size of the buffer it's to read into, so
  2277.         it cannot be prevented from overflowing that buffer.
  2278.  
  2279. 11.6:   Why does errno contain ENOTTY after a call to printf?
  2280.  
  2281. A:      Many implementations of the stdio package adjust their behavior
  2282.         slightly if stdout is a terminal.  To make the determination,
  2283.         these implementations perform an operation which fails (with
  2284.         ENOTTY) if stdout is not a terminal.  Although the output
  2285.         operation goes on to complete successfully, errno still contains
  2286.         ENOTTY.
  2287.  
  2288.         References: CT&P Sec. 5.4 p. 73.
  2289.  
  2290. 11.7:   My program's prompts and intermediate output don't always show
  2291.         up on the screen, especially when I pipe the output through
  2292.         another program.
  2293.  
  2294. A:      It is best to use an explicit fflush(stdout) whenever output
  2295.         should definitely be visible.  Several mechanisms attempt to
  2296.         perform the fflush for you, at the "right time," but they tend
  2297.         to apply only when stdout is a terminal.  (See question 11.6.)
  2298.  
  2299. 11.8:   When I read from the keyboard with scanf, it seems to hang until
  2300.         I type one extra line of input.
  2301.  
  2302. A:      scanf was designed for free-format input, which is seldom what
  2303.         you want when reading from the keyboard.  In particular, "\n" in
  2304.         a format string does _not_ mean to expect a newline, but rather
  2305.         to read and discard characters as long as each is a whitespace
  2306.         character.
  2307.  
  2308.         A related problem is that unexpected non-numeric input can cause
  2309.         scanf to "jam."  Because of these problems, it is usually better
  2310.         to use fgets() to read a whole line, and then use sscanf or
  2311.         other string functions to pick apart the line buffer.  If you do
  2312.         use sscanf, don't forget to check the return value to make sure
  2313.         that the expected number of items were found.
  2314.  
  2315. 11.9:   I'm trying to update a file in place, by using fopen mode "r+",
  2316.         then reading a certain string, and finally writing back a
  2317.         modified string, but it's not working.
  2318.  
  2319. A:      Be sure to call fseek before you write, both to seek back to the
  2320.         beginning of the string you're trying to overwrite, and because
  2321.         an fseek or fflush is always required between reading and
  2322.         writing in the read/write "+" modes.
  2323.  
  2324.         References: ANSI Sec. 4.9.5.3 p. 131.
  2325.  
  2326. 11.10:  How can I read one character at a time, without waiting for the
  2327.         RETURN key?
  2328.  
  2329. A:      See question 16.1.
  2330.  
  2331. 11.11:  How can I flush pending input so that a user's typeahead isn't
  2332.         read at the next prompt?  Will fflush(stdin) work?
  2333.  
  2334. A:      fflush is defined only for output streams.  Since its definition
  2335.         of "flush" is to complete the writing of buffered characters
  2336.         (not to discard them), discarding unread input would not be an
  2337.         analogous meaning for fflush on input streams.  There is no
  2338.         standard way to discard unread characters from a stdio input
  2339.         buffer, nor would such a way be sufficient; unread characters
  2340.         can also accumulate in other, OS-level input buffers.
  2341.  
  2342. 11.12:  How can I redirect stdin or stdout to a file from within a
  2343.         program?
  2344.  
  2345. A:      Use freopen.
  2346.  
  2347. 11.13:  Once I've used freopen, how can I get the original stdout (or
  2348.         stdin) back?
  2349.  
  2350. A:      If you need to switch back and forth, the best all-around
  2351.         solution is not to use freopen in the first place.  Try using
  2352.         your own explicit output (or input) stream variable, which you
  2353.         can reassign at will, while leaving the original stdout (or
  2354.         stdin) undisturbed.
  2355.  
  2356. 11.14:  How can I recover the file name given an open file descriptor?
  2357.  
  2358. A:      This problem is, in general, insoluble.  Under Unix, for
  2359.         instance, a scan of the entire disk, (perhaps requiring special
  2360.         permissions) would theoretically be required, and would fail if
  2361.         the file descriptor was a pipe or referred to a deleted file
  2362.         (and could give a misleading answer for a file with multiple
  2363.         links).  It is best to remember the names of files yourself when
  2364.         you open them (perhaps with a wrapper function around fopen).
  2365.  
  2366.  
  2367. Section 12. Library Subroutines
  2368.  
  2369. 12.1:   Why does strncpy not always place a '\0' termination in the
  2370.         destination string?
  2371.  
  2372. A:      strncpy was first designed to handle a now-obsolete data
  2373.         structure, the fixed-length, not-necessarily-\0-terminated
  2374.         "string."  strncpy is admittedly a bit cumbersome to use in
  2375.         other contexts, since you must often append a '\0' to the
  2376.         destination string by hand.
  2377.  
  2378. 12.2:   I'm trying to sort an array of strings with qsort, using strcmp
  2379.         as the comparison function, but it's not working.
  2380.  
  2381. A:      By "array of strings" you probably mean "array of pointers to
  2382.         char."  The arguments to qsort's comparison function are
  2383.         pointers to the objects being sorted, in this case, pointers to
  2384.         pointers to char.  (strcmp, of course, accepts simple pointers
  2385.         to char.)
  2386.  
  2387.         The comparison routine's arguments are expressed as "generic
  2388.         pointers," const void * or char *.  They must be converted back
  2389.         to what they "really are" (char **) and dereferenced, yielding
  2390.         char *'s which can be usefully compared.  Write a comparison
  2391.         function like this:
  2392.  
  2393.                 int pstrcmp(p1, p2)     /* compare strings through pointers */
  2394.                 char *p1, *p2;          /* const void * for ANSI C */
  2395.                 {
  2396.                         return strcmp(*(char **)p1, *(char **)p2);
  2397.                 }
  2398.  
  2399. 12.3:   Now I'm trying to sort an array of structures with qsort.  My
  2400.         comparison routine takes pointers to structures, but the
  2401.         compiler complains that the function is of the wrong type for
  2402.         qsort.  How can I cast the function pointer to shut off the
  2403.         warning?
  2404.  
  2405. A:      The conversions must be in the comparison function, which must
  2406.         be declared as accepting "generic pointers" (const void * or
  2407.         char *) as discussed above.
  2408.  
  2409. 12.4:   How can I convert numbers to strings (the opposite of atoi)?  Is
  2410.         there an itoa function?
  2411.  
  2412. A:      Just use sprintf.  (You'll have to allocate space for the result
  2413.         somewhere anyway; see questions 3.1 and 3.2.  Don't worry that
  2414.         sprintf may be overkill, potentially wasting run time or code
  2415.         space; it works well in practice.)
  2416.  
  2417.         References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64.
  2418.  
  2419. 12.5:   How can I get the current date or time of day in a C program?
  2420.  
  2421. A:      Just use the time, ctime, and/or localtime functions.  (These
  2422.         routines have been around for years, and are in the ANSI
  2423.         standard.)  Here is a simple example:
  2424.  
  2425.                 #include <stdio.h>
  2426.                 #include <time.h>
  2427.  
  2428.                 main()
  2429.                 {
  2430.                         time_t now;
  2431.                         time(&now);
  2432.                         printf("It's %.24s.\n", ctime(&now));
  2433.                         return 0;
  2434.                 }
  2435.  
  2436.         References: ANSI Sec. 4.12 .
  2437.  
  2438. 12.6:   I know that the library routine localtime will convert a time_t
  2439.         into a broken-down struct tm, and that ctime will convert a
  2440.         time_t to a printable string.  How can I perform the inverse
  2441.         operations of converting a struct tm or a string into a time_t?
  2442.  
  2443. A:      ANSI C specifies a library routine, mktime, which converts a
  2444.         struct tm to a time_t.  Several public-domain versions of this
  2445.         routine are available in case your compiler does not support it
  2446.         yet.
  2447.  
  2448.         Converting a string to a time_t is harder, because of the wide
  2449.         variety of date and time formats which should be parsed.
  2450.         Public-domain routines have been written for performing this
  2451.         function (see, for example, the file partime.c, widely
  2452.         distributed with the RCS package), but they are less likely to
  2453.         become standardized.
  2454.  
  2455.         References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  2456.         Sec. 4.12.2.3 .
  2457.  
  2458. 12.7:   I need a random number generator.
  2459.  
  2460. A:      The standard C library has one: rand().  The implementation on
  2461.         your system may not be perfect, but writing a better one isn't
  2462.         necessarily easy, either.
  2463.  
  2464.         References: ANSI Sec. 4.10.2.1 p. 154, Knuth Vol. 2 Chap. 3
  2465.         pp. 1-177.
  2466.  
  2467. 12.8:   Each time I run my program, I get the same sequence of numbers
  2468.         back from rand().
  2469.  
  2470. A:      You can call srand() to seed the pseudo-random number generator
  2471.         with a more random initial value.  Popular seed values are the
  2472.         time of day, or the elapsed time before the user presses a key
  2473.         (although keypress times are hard to determine portably; see
  2474.         question 16.9).
  2475.  
  2476.         References: ANSI Sec. 4.10.2.2 p. 154.
  2477.  
  2478. 12.9:   I need a random true/false value, so I'm taking rand() % 2, but
  2479.         it's just alternating 0, 1, 0, 1, 0...
  2480.  
  2481. A:      Poor pseudorandom number generators (such as the ones
  2482.         unfortunately supplied with some systems) are not very random in
  2483.         the low-order bits.  Try using the higher-order bits.
  2484.  
  2485. 12.10-  I'm trying to port this old     A:  These routines are variously
  2486.  12.14: program.  Why do I get              obsolete; you should
  2487.         "undefined external" errors         instead:
  2488.         for:
  2489.  
  2490. 12.10:  index?                          A:  use strchr.
  2491. 12.11:  rindex?                         A:  use strrchr.
  2492. 12.12:  bcopy?                          A:  use memmove, after
  2493.                                             interchanging the first and
  2494.                                             second arguments (see also
  2495.                                             question 5.13).
  2496. 12.13:  bcmp?                           A:  use memcmp.
  2497. 12.14:  bzero?                          A:  use memset, with a second
  2498.                                             argument of 0.
  2499.  
  2500. 12.15:  How can I execute a command with system() and read its output
  2501.         into a program?
  2502.  
  2503. A:      Unix and some other systems provide a popen() routine, which
  2504.         sets up a stdio stream on a pipe connected to the process
  2505.         running a command, so that the output can be read (or the input
  2506.         supplied).
  2507.  
  2508. 12.16:  How can I read a directory in a C program?
  2509.  
  2510. A:      See if you can use the opendir() and readdir() routines, which
  2511.         are available on most Unix systems.  Implementations also exist
  2512.         for MS-DOS, VMS, and other systems.  (MS-DOS also has FINDFIRST
  2513.         and FINDNEXT routines which do essentially the same thing.)
  2514.  
  2515.  
  2516. Section 13. Lint
  2517.  
  2518. 13.1:   I just typed in this program, and it's acting strangely.  Can
  2519.         you see anything wrong with it?
  2520.  
  2521. A:      Try running lint first(perhaps with the -a, -c, -h, -p and/or
  2522.         other options).  Many C compilers are really only half-
  2523.         compilers, electing not to diagnose numerous source code
  2524.         difficulties which would not actively preclude code generation.
  2525.  
  2526. 13.2:   How can I shut off the "warning: possible pointer alignment
  2527.         problem" message lint gives me for each call to malloc?
  2528.  
  2529. A:      The problem is that traditional versions of lint do not know,
  2530.         and cannot be told, that malloc "returns a pointer to space
  2531.         suitably aligned for storage of any type of object."  It is
  2532.         possible to provide a pseudoimplementation of malloc, using a
  2533.         #define inside of #ifdef lint, which effectively shuts this
  2534.         warning off, but a simpleminded #definition will also suppress
  2535.         meaningful messages about truly incorrect invocations.  It may
  2536.         be easier simply to ignore the message, perhaps in an automated
  2537.         way with grep -v.
  2538.  
  2539. 13.3:   Where can I get an ANSI-compatible lint?
  2540.  
  2541. A:      A product called FlexeLint is available (in "shrouded source
  2542.         form," for compilation on 'most any system) from
  2543.  
  2544.                 Gimpel Software
  2545.                 3207 Hogarth Lane
  2546.                 Collegeville, PA  19426  USA
  2547.                 (+1) 215 584 4261
  2548.  
  2549.         The System V release 4 lint is ANSI-compatible, and is available
  2550.         separately (bundled with other C tools) from Unix Support Labs
  2551.         (a subsidiary of AT&T), or from System V resellers.
  2552.  
  2553.  
  2554. Section 14. Style
  2555.  
  2556. 14.1:   Here's a neat trick:
  2557.  
  2558.                 if(!strcmp(s1, s2))
  2559.  
  2560.         Is this good style?
  2561.  
  2562. A:      It is not particularly good style, although it is a popular
  2563.         idiom.  The test succeeds if the two strings are equal, but its
  2564.         form suggests that it tests for inequality.
  2565.  
  2566.         Another solution is to use a macro:
  2567.  
  2568.                 #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  2569.  
  2570.         Opinions on code style, like those on religion, can be debated
  2571.         endlessly.  Though good style is a worthy goal, and can usually
  2572.         be recognized, it cannot be codified.
  2573.  
  2574. 14.2:   What's the best style for code layout in C?
  2575.  
  2576. A:      K&R, while providing the example most often copied, also supply
  2577.         a good excuse for avoiding it:
  2578.  
  2579.                 The position of braces is less important,
  2580.                 although people hold passionate beliefs.
  2581.                 We have chosen one of several popular styles.
  2582.                 Pick a style that suits you, then use it
  2583.                 consistently.
  2584.  
  2585.         It is more important that the layout chosen be consistent (with
  2586.         itself, and with nearby or common code) than that it be
  2587.         "perfect."  If your coding environment (i.e. local custom or
  2588.         company policy) does not suggest a style, and you don't feel
  2589.         like inventing your own, just copy K&R.  (The tradeoffs between
  2590.         various indenting and brace placement options can be
  2591.         exhaustively and minutely examined, but don't warrant repetition
  2592.         here.  See also the Indian Hill Style Guide.)
  2593.  
  2594.         The elusive quality of "good style" involves much more than mere
  2595.         code layout details; don't spend time on formatting to the
  2596.         exclusion of more substantive code quality issues.
  2597.  
  2598.         References: K&R Sec. 1.2 p. 10.
  2599.  
  2600. 14.3:   Where can I get the "Indian Hill Style Guide" and other coding
  2601.         standards?
  2602.  
  2603. A:      Various documents are available for anonymous ftp from:
  2604.  
  2605.                 Site:                   File or directory:
  2606.  
  2607.                 cs.washington.edu       ~ftp/pub/cstyle.tar.Z
  2608.                 (128.95.1.4)            (the updated Indian Hill guide)
  2609.  
  2610.                 cs.toronto.edu          doc/programming
  2611.  
  2612.                 giza.cis.ohio-state.edu pub/style-guide
  2613.  
  2614.  
  2615. Section 15. Floating Point
  2616.  
  2617. 15.1:   My floating-point calculations are acting strangely and giving
  2618.         me different answers on different machines.
  2619.  
  2620. A:      First, make sure that you have #included <math.h>, and correctly
  2621.         declared other functions returning double.
  2622.  
  2623.         If the problem isn't that simple, recall that most digital
  2624.         computers use floating-point formats which provide a close but
  2625.         by no means exact simulation of real number arithmetic.
  2626.         Underflow, cumulative precision loss, and other anomalies are
  2627.         often troublesome.
  2628.  
  2629.         Don't assume that floating-point results will be exact, and
  2630.         especially don't assume that floating-point values can be
  2631.         compared for equality.  (Don't throw haphazard "fuzz factors"
  2632.         in, either.)
  2633.  
  2634.         These problems are no worse for C than they are for any other
  2635.         computer language.  Floating-point semantics are usually defined
  2636.         as "however the processor does them;" otherwise a compiler for a
  2637.         machine without the "right" model would have to do prohibitively
  2638.         expensive emulations.
  2639.  
  2640.         This article cannot begin to list the pitfalls associated with,
  2641.         and workarounds appropriate for, floating-point work.  A good
  2642.         programming text should cover the basics.
  2643.  
  2644.         References: EoPS Sec. 6 pp. 115-8.
  2645.  
  2646. 15.2:   I'm trying to do some simple trig, and I am #including <math.h>,
  2647.         but I keep getting "undefined: _sin" compilation errors.
  2648.  
  2649. A:      Make sure you're linking against the correct math library.  For
  2650.         instance, under Unix, you usually need to use the -lm option,
  2651.         and at the _end_ of the command line, when compiling/linking.
  2652.  
  2653. 15.3:   Why doesn't C have an exponentiation operator?
  2654.  
  2655. A:      You can #include <math.h> and use the pow() function, although
  2656.         explicit multiplication is often better for small positive
  2657.         integral exponents.
  2658.  
  2659.         References: ANSI Sec. 4.5.5.1 .
  2660.  
  2661. 15.4:   I'm having trouble with a Turbo C program which crashes and says
  2662.         something like "floating point formats not linked."
  2663.  
  2664. A:      Some compilers for small machines, including Turbo C (and
  2665.         Ritchie's original PDP-11 compiler), leave out floating point
  2666.         support if it looks like it will not be needed.  In particular,
  2667.         the non-floating-point versions of printf and scanf save space
  2668.         by not including code to handle %e, %f, and %g.  It happens that
  2669.         Turbo C's heuristics for determining whether the program uses
  2670.         floating point are insufficient, and the programmer must
  2671.         sometimes insert an extra, explicit call to a floating-point
  2672.         library routine to force loading of floating-point support.
  2673.  
  2674.  
  2675. Section 16. System Dependencies
  2676.  
  2677. 16.1:   How can I read a single character from the keyboard without
  2678.         waiting for a newline?
  2679.  
  2680. A:      Contrary to popular belief and many people's wishes, this is not
  2681.         a C-related question.  (Nor are closely-related questions
  2682.         concerning the echo of keyboard input.)  The delivery of
  2683.         characters from a "keyboard" to a C program is a function of the
  2684.         operating system in use, and has not been standardized by the C
  2685.         language.  Some versions of curses have a cbreak() function
  2686.         which does what you want.  Under UNIX, use ioctl to play with
  2687.         the terminal driver modes (CBREAK or RAW under "classic"
  2688.         versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or
  2689.         Posix systems).  Under MS-DOS, use getch().  Under VMS, try the
  2690.         Screen Management (SMG$) routines, or curses, or issue low-level
  2691.         $QIO's to ask for one character at a time.  Under other
  2692.         operating systems, you're on your own.  Beware that some
  2693.         operating systems make this sort of thing impossible, because
  2694.         character collection into input lines is done by peripheral
  2695.         processors not under direct control of the CPU running your
  2696.         program.
  2697.  
  2698.         Operating system specific questions are not appropriate for
  2699.         comp.lang.c .  Many common questions are answered in
  2700.         frequently-asked questions postings in such groups as
  2701.         comp.unix.questions and comp.os.msdos.programmer .  Note that
  2702.         the answers are often not unique even across different variants
  2703.         of a system; bear in mind when answering system-specific
  2704.         questions that the answer that applies to your system may not
  2705.         apply to everyone else's.
  2706.  
  2707.         References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  2708.  
  2709. 16.2:   How can I find out if there are characters available for reading
  2710.         (and if so, how many)?  Alternatively, how can I do a read that
  2711.         will not block if there are no characters available?
  2712.  
  2713. A:      These, too, are entirely operating-system-specific.  Some
  2714.         versions of curses have a nodelay() function.  Depending on your
  2715.         system, you may also be able to use "nonblocking I/O", or a
  2716.         system call named "select", or the FIONREAD ioctl, or kbhit(),
  2717.         or rdchk(), or the O_NDELAY option to open() or fcntl().
  2718.  
  2719. 16.3:   How can I clear the screen?  How can I print things in inverse
  2720.         video?
  2721.  
  2722. A:      Such things depend on the terminal type (or display) you're
  2723.         using.  You will have to use a library such as termcap or
  2724.         curses, or some system-specific routines, to perform these
  2725.         functions.
  2726.  
  2727. 16.4:   How do I read the mouse?
  2728.  
  2729. A:      Consult your system documentation, or ask on an appropriate
  2730.         system-specific newsgroup (but check its FAQ list first).  Mouse
  2731.         handling is completely different under the X window system, MS-
  2732.         DOS, Macintosh, and probably every other system.
  2733.  
  2734. 16.5:   How can my program discover the complete pathname to the
  2735.         executable file from which it was invoked?
  2736.  
  2737. A:      argv[0] may contain all or part of the pathname, or it may
  2738.         contain nothing.  You may be able to duplicate the command
  2739.         language interpreter's search path logic to locate the
  2740.         executable if the name in argv[0] is present but incomplete.
  2741.         However, there is no guaranteed or portable solution.
  2742.  
  2743. 16.6:   How can a process change an environment variable in its caller?
  2744.  
  2745. A:      In general, it cannot.  Different operating systems implement
  2746.         name/value functionality similar to the Unix environment in
  2747.         different ways.  Whether the "environment" can be usefully
  2748.         altered by a running program, and if so, how, is system-
  2749.         dependent.
  2750.  
  2751.         Under Unix, a process can modify its own environment (some
  2752.         systems provide setenv() and/or putenv() functions to do this),
  2753.         and the modified environment is usually passed on to any child
  2754.         processes, but it is _not_ propagated back to the parent
  2755.         process.
  2756.  
  2757. 16.7:   How can I find out the size of a file, prior to reading it in?
  2758.  
  2759. A:      If the "size of a file" is the number of characters you'll be
  2760.         able to read from it in C, it is in general impossible to
  2761.         determine this number in advance.  Under Unix, the stat call
  2762.         will give you an exact answer, and several other systems supply
  2763.         a Unix-like stat which will give an approximate answer.  You can
  2764.         fseek to the end and then use ftell, but this usage is
  2765.         nonportable (it gives you an accurate answer only under Unix,
  2766.         and otherwise a quasi-accurate answer only for ANSI C "binary"
  2767.         files).
  2768.  
  2769.         Are you sure you have to determine the file's size in advance?
  2770.         Since the most accurate way of determining the size of a file as
  2771.         a C program will see it is to open the file and read it, perhaps
  2772.         you can rearrange the code to learn the size as it reads.
  2773.  
  2774. 16.8:   How can a file be shortened in-place without completely clearing
  2775.         or rewriting it?
  2776.  
  2777. A:      BSD systems provide ftruncate(), several others supply chsize(),
  2778.         and a few may provide a (possibly undocumented) fcntl option
  2779.         F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  2780.         However, there is no truly portable solution.
  2781.  
  2782. 16.9:   How can I implement a delay, or time a user's response, with
  2783.         sub-second resolution?
  2784.  
  2785. A:      Unfortunately, there is no portable way.  V7 Unix, and derived
  2786.         systems, provided a fairly useful ftime() routine with
  2787.         resolution up to a millisecond, but it has disappeared from
  2788.         System V and Posix.  Other routines you might look for on your
  2789.         system include clock() and gettimeofday().  The select() and
  2790.         poll() calls (if available) can be pressed into service to
  2791.         implement simple delays.  On MS-DOS machines, it is possible to
  2792.         reprogram the system timer and timer interrupts.
  2793.  
  2794. 16.10:  How can I read in an object file and jump to routines in it?
  2795.  
  2796. A:      You want a dynamic linker and/or loader.  It is possible to
  2797.         malloc some space and read in object files, but you have to know
  2798.         an awful lot about object file formats, relocation, etc.  Under
  2799.         BSD Unix, you could use system() and ld -A to do the linking for
  2800.         you.  Many (most?) versions of SunOS and System V have the -ldl
  2801.         library which allows object files to be dynamically loaded.
  2802.         There is also a GNU package called "dld".  See also question
  2803.         7.6.
  2804.  
  2805.  
  2806. Section 17. Miscellaneous
  2807.  
  2808. 17.1:   What can I safely assume about the initial values of variables
  2809.         which are not explicitly initialized?  If global variables start
  2810.         out as "zero," is that good enough for null pointers and
  2811.         floating-point zeroes?
  2812.  
  2813. A:      Variables with "static" duration (that is, those declared
  2814.         outside of functions, and those declared with the storage class
  2815.         static), are guaranteed initialized to zero, as if the
  2816.         programmer had typed "= 0".  Therefore, such variables are
  2817.         initialized to the null pointer (of the correct type) if they
  2818.         are pointers, and to 0.0 if they are floating-point.
  2819.  
  2820.         Variables with "automatic" duration (i.e. local variables
  2821.         without the static storage class) start out containing garbage,
  2822.         unless they are explicitly initialized.  Nothing useful can be
  2823.         predicted about the garbage.
  2824.  
  2825.         Dynamically-allocated memory obtained with malloc and realloc is
  2826.         also likely to contain garbage, and must be initialized by the
  2827.         calling program, as appropriate.  Memory obtained with calloc
  2828.         contains all-bits-0, but this is not necessarily useful for
  2829.         pointer or floating-point values (see question 3.11, and section
  2830.         1).
  2831.  
  2832. 17.2:   How can I write data files which can be read on other machines
  2833.         with different word size, byte order, or floating point formats?
  2834.  
  2835. A:      The best solution is to use text files (usually ASCII), written
  2836.         with fprintf and read with fscanf or the like.  (Similar advice
  2837.         also applies to network protocols.)  Be skeptical of arguments
  2838.         which imply that text files are too big, or that reading and
  2839.         writing them is too slow.  Not only is their efficiency
  2840.         frequently acceptable in practice, but the advantages of being
  2841.         able to manipulate them with standard tools can be overwhelming.
  2842.         If you must use a binary format, you can improve portability,
  2843.         and perhaps take advantage of prewritten I/O libraries, by
  2844.         making use of standardized formats such as Sun's XDR (RFC 1014),
  2845.         OSI's ASN.1, CCITT's X.409, or ISO 8825 "Basic Encoding Rules."
  2846.         See also question 9.10.
  2847.  
  2848. 17.3:   How can I return several values from a function?
  2849.  
  2850. A:      Either pass pointers to locations which the function can fill
  2851.         in, or have the function return a structure containing the
  2852.         desired values, or (in a pinch) consider global variables.  See
  2853.         also questions 2.16, 3.4, and 9.2.
  2854.  
  2855. 17.4:   If I have a char * variable pointing to the name of a function
  2856.         as a string, how can I call that function?
  2857.  
  2858. A:      The most straightforward thing to do is maintain a
  2859.         correspondence table of names and function pointers:
  2860.  
  2861.                 int function1(), function2();
  2862.  
  2863.                 struct {char *name; int (*funcptr)(); } symtab[] =
  2864.                         {
  2865.                         "function1",    function1,
  2866.                         "function2",    function2,
  2867.                         };
  2868.  
  2869.         Then, just search the table for the name, and call through the
  2870.         associated function pointer.
  2871.  
  2872. 17.5:   I seem to be missing the system header file <sgtty.h>.  Can
  2873.         someone send me a copy?
  2874.  
  2875. A:      Standard headers exist in part so that definitions appropriate
  2876.         to your compiler, operating system, and processor can be
  2877.         supplied.  You cannot just pick up a copy of someone else's
  2878.         header file and expect it to work, unless that person is using
  2879.         exactly the same environment.  Ask your compiler vendor why the
  2880.         file was not provided (or to send a replacement copy).
  2881.  
  2882. 17.6:   How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  2883.         from C?  (And vice versa?)
  2884.  
  2885. A:      The answer is entirely dependent on the machine and the specific
  2886.         calling sequences of the various compilers in use, and may not
  2887.         be possible at all.  Read your compiler documentation very
  2888.         carefully; sometimes there is a "mixed-language programming
  2889.         guide," although the techniques for passing arguments and
  2890.         ensuring correct run-time startup are often arcane.  More
  2891.         information may be found in FORT.Z by Glenn Geers, available via
  2892.         anonymous ftp from suphys.physics.su.oz.au in the src directory.
  2893.  
  2894.         cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  2895.         many popular machines.  It is available via anonymous ftp from
  2896.         zebra.desy.de (131.169.2.244).
  2897.  
  2898.         In C++, a "C" modifier in an external function declaration
  2899.         indicates that the function is to be called using C calling
  2900.         conventions.
  2901.  
  2902. 17.7:   Does anyone know of a program for converting Pascal or FORTRAN
  2903.         (or LISP, Ada, awk, "Old" C, ...) to C?
  2904.  
  2905. A:      Several public-domain programs are available:
  2906.  
  2907.         p2c     written by Dave Gillespie, and posted to
  2908.                 comp.sources.unix in March, 1990 (Volume 21); also
  2909.                 available by anonymous ftp from csvax.cs.caltech.edu,
  2910.                 file pub/p2c-1.20.tar.Z .
  2911.  
  2912.         ptoc    another comp.sources.unix contribution, this one written
  2913.                 in Pascal (comp.sources.unix, Volume 10, also patches in
  2914.                 Volume 13?).
  2915.  
  2916.         f2c     jointly developed by people from Bell Labs, Bellcore,
  2917.                 and Carnegie Mellon.  To find about f2c, send the mail
  2918.                 message "send index from f2c" to netlib@research.att.com
  2919.                 or research!netlib.  (It is also available via anonymous
  2920.                 ftp on research.att.com, in directory dist/f2c.)
  2921.  
  2922.         This FAQ list's maintainer also has available a list of other
  2923.         commercial translation products, and some for more obscure
  2924.         languages.
  2925.  
  2926.         See also question 5.3.
  2927.  
  2928. 17.8:   Where can I get copies of all these public-domain programs?
  2929.  
  2930. A:      If you have access to Usenet, see the regular postings in the
  2931.         comp.sources.unix and comp.sources.misc newsgroups, which
  2932.         describe, in some detail, the archiving policies and how to
  2933.         retrieve copies.  The usual approach is to use anonymous ftp
  2934.         and/or uucp from a central, public-spirited site, such as uunet
  2935.         (ftp.uu.net, 192.48.96.9).  However, this article cannot track
  2936.         or list all of the available archive sites and how to access
  2937.         them.  The comp.archives newsgroup contains numerous
  2938.         announcements of anonymous ftp availability of various items.
  2939.         The "archie" mailserver can tell you which anonymous ftp sites
  2940.         have which packages; send the mail message "help" to
  2941.         archie@quiche.cs.mcgill.ca for information.  Finally, the
  2942.         newsgroup comp.sources.wanted is generally a more appropriate
  2943.         place to post queries for source availability, but check _its_
  2944.         FAQ list, "How to find sources," before posting there.
  2945.  
  2946. 17.9:   When will the next International Obfuscated C Code Contest
  2947.         (IOCCC) be held?  How can I get a copy of the current and
  2948.         previous winning entries?
  2949.  
  2950. A:      The contest typically runs from early March through mid-May.  To
  2951.         obtain a current copy of the rules and guidelines, send e-mail
  2952.         with the Subject: line "send rules" to:
  2953.  
  2954.                 {apple,pyramid,sun,uunet}!hoptoad!judges  (not the addresses for
  2955.         or      judges@toad.com                            submitting entries)
  2956.  
  2957.         Contest winners are first announced at the Summer Usenix
  2958.         Conference in mid-June, and posted to the net sometime in July-
  2959.         August.  Winning entries from previous years (to 1984) are
  2960.         archived at uunet (see question 17.8) under the directory
  2961.         ~/pub/ioccc.
  2962.  
  2963.         As a last resort, previous winners may be obtained by sending
  2964.         e-mail to the above address, using the Subject: "send YEAR
  2965.         winners", where YEAR is a single four-digit year, a year range,
  2966.         or "all".
  2967.  
  2968. 17.10:  Why don't C comments nest?  Are they legal inside quoted
  2969.         strings?
  2970.  
  2971. A:      Nested comments would cause more harm than good, mostly because
  2972.         of the possibility of accidentally leaving comments unclosed by
  2973.         including the characters "/*" within them.  For this reason, it
  2974.         is usually better to "comment out" large sections of code, which
  2975.         might contain comments, with #ifdef or #if 0 (but see question
  2976.         5.9).
  2977.  
  2978.         The character sequences /* and */ are not special within
  2979.         double-quoted strings, and do not therefore introduce comments,
  2980.         because a program (particularly one which is generating C code
  2981.         as output) might want to print them.
  2982.  
  2983.         References: ANSI Appendix E p. 198, Rationale Sec. 3.1.9 p. 33.
  2984.  
  2985. 17.11:  How can I implement sets and/or arrays of bits?
  2986.  
  2987. A:      Use arrays of char or int, with a few macros to access the right
  2988.         bit at the right index (try using 8 for CHAR_BIT if you don't
  2989.         have <limits.h>):
  2990.  
  2991.                 #include <limits.h>             /* for CHAR_BIT */
  2992.  
  2993.                 #define BITMASK(bit) (1 << ((bit) % CHAR_BIT))
  2994.                 #define BITSLOT(bit) ((bit) / CHAR_BIT)
  2995.                 #define BITSET(ary, bit) ((ary)[BITSLOT(bit)] |= BITMASK(bit))
  2996.                 #define BITTEST(ary, bit) ((ary)[BITSLOT(bit)] & BITMASK(bit))
  2997.  
  2998. 17.12:  What is the most efficient way to count the number of bits which
  2999.         are set in a value?
  3000.  
  3001. A:      This and many other similar bit-twiddling problems can often be
  3002.         sped up and streamlined using lookup tables (but see the next
  3003.         question).
  3004.  
  3005. 17.13:  How can I make this code more efficient?
  3006.  
  3007. A:      Efficiency, though a favorite comp.lang.c topic, is not
  3008.         important nearly as often as people tend to think it is.  Most
  3009.         of the code in most programs is not time-critical.  When code is
  3010.         not time-critical, it is far more important that it be written
  3011.         clearly and portably than that it be written maximally
  3012.         efficiently.  (Remember that computers are very, very fast, and
  3013.         that even "inefficient" code can run without apparent delay.)
  3014.  
  3015.         It is notoriously difficult to predict what the "hot spots" in a
  3016.         program will be.  When efficiency is a concern, it is important
  3017.         to use profiling software to determine which parts of the
  3018.         program deserve attention.  Often, actual computation time is
  3019.         swamped by peripheral tasks such as I/O and memory allocation,
  3020.         which can be sped up by using buffering and cacheing techniques.
  3021.  
  3022.         For the small fraction of code that is time-critical, it is
  3023.         vital to pick a good algorithm; it is less important to
  3024.         "microoptimize" the coding details.  Many of the "efficient
  3025.         coding tricks" which are frequently suggested (e.g. substituting
  3026.         shift operators for multiplication by powers of two) are
  3027.         performed automatically by even simpleminded compilers.
  3028.         Heavyhanded "optimization" attempts can make code so bulky that
  3029.         performance is degraded.
  3030.  
  3031.         For more discussion of efficiency tradeoffs, as well as good
  3032.         advice on how to increase efficiency when it is important, see
  3033.         chapter 7 of Kernighan and Plauger's The Elements of Programming
  3034.         Style, and Jon Bentley's Writing Efficient Programs.
  3035.  
  3036. 17.14:  Are pointers really faster than arrays?  How much do function
  3037.         calls slow things down?  Is ++i faster than i = i + 1?
  3038.  
  3039. A:      Precise answers to these and many similar questions depend of
  3040.         course on the processor and compiler in use.  If you simply must
  3041.         know, you'll have to time test programs carefully.  (Often the
  3042.         differences are so slight that hundreds of thousands of
  3043.         iterations are required even to see them.  Check the compiler's
  3044.         assembly language output, if available, to see if two purported
  3045.         alternatives aren't compiled identically.)
  3046.  
  3047.         It is "usually" faster to march through large arrays with
  3048.         pointers rather than array subscripts, but for some processors
  3049.         the reverse is true.
  3050.  
  3051.         Function calls, though obviously incrementally slower than in-
  3052.         line code, contribute so much to modularity and code clarity
  3053.         that there is rarely good reason to avoid them.
  3054.  
  3055.         Before rearranging expressions such as i = i + 1, remember that
  3056.         you are dealing with a C compiler, not a keystroke-programmable
  3057.         calculator.  Any decent compiler will generate identical code
  3058.         for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  3059.         i += 1 over i = i + 1 have to do with style, not efficiency.
  3060.         (See also question 4.4.)
  3061.  
  3062. 17.15:  This program crashes before it even runs!  (When single-stepping
  3063.         with a debugger, it dies before the first statement in main.)
  3064.  
  3065. A:      You probably have one or more very large (kilobyte or more)
  3066.         local arrays.  Many systems have fixed-size stacks, and those
  3067.         which perform dynamic stack allocation automatically (e.g. Unix)
  3068.         can be confused when the stack tries to grow by a huge chunk all
  3069.         at once.
  3070.  
  3071.         It is often better to declare large arrays with static duration
  3072.         (unless of course you need a fresh set with each recursive
  3073.         call).
  3074.  
  3075.         (See also question 9.4.)
  3076.  
  3077. 17.16:  What do "Segmentation violation" and "Bus error" mean?
  3078.  
  3079. A:      These generally mean that your program tried to access memory it
  3080.         shouldn't have, invariably as a result of improper pointer use,
  3081.         often involving malloc (see question 17.17) or perhaps scanf
  3082.         (see question 11.2).
  3083.  
  3084. 17.17:  My program is crashing, apparently somewhere down inside malloc,
  3085.         but I can't see anything wrong with it.
  3086.  
  3087. A:      It is unfortunately very easy to corrupt malloc's internal data
  3088.         structures, and the resulting problems can be hard to track
  3089.         down.  The most common source of problems is writing more to a
  3090.         malloc'ed region than it was allocated to hold; a particularly
  3091.         common bug is to malloc(strlen(s)) instead of strlen(s) + 1.
  3092.         Other problems involve freeing pointers not obtained from
  3093.         malloc, or trying to realloc a null pointer (see question 3.10).
  3094.  
  3095.         A number of debugging packages exist to help track down malloc
  3096.         problems; one popular one is Conor P. Cahill's "dbmalloc".
  3097.  
  3098. 17.18:  Does anyone have a C compiler test suite I can use?
  3099.  
  3100. A:      Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA) sells one.
  3101.         The FSF's GNU C (gcc) distribution includes a c-torture-
  3102.         test.tar.Z which checks a number of common problems with
  3103.         compilers.  Kahan's paranoia test, found in netlib on
  3104.         research.att.com, strenuously tests a C implementation's
  3105.         floating point capabilities.
  3106.  
  3107. 17.19:  Where can I get a YACC grammar for C?
  3108.  
  3109. A:      The definitive grammar is of course the one in the ANSI
  3110.         standard.  Several copies are floating around; keep your eyes
  3111.         open.  There is one (due to Jeff Lee) on uunet (see question
  3112.         17.8) in usenet/net.sources/ansi.c.grammar.Z (including a
  3113.         companion lexer).  Another one, by Jim Roskind, is in
  3114.         pub/*grammar* at ics.uci.edu .  The FSF's GNU C compiler
  3115.         contains a grammar, as does the appendix to K&R II.
  3116.  
  3117.         References: ANSI Sec. A.2 .
  3118.  
  3119. 17.20:  How do you pronounce "char"?
  3120.  
  3121. A:      You can pronounce the C keyword "char" in at least three ways:
  3122.         like the English words "char," "care," or "car;" the choice is
  3123.         arbitrary.
  3124.  
  3125. 17.21:  What's a good book for learning C?
  3126.  
  3127. A:      Mitch Wright maintains an annotated bibliography of C and Unix
  3128.         books; it is available for anonymous ftp from ftp.rahul.net in
  3129.         directory pub/mitch/YABL.
  3130.  
  3131.         This FAQ list's editor maintains a collection of previous
  3132.         answers to this question, which is available upon request.
  3133.  
  3134. 17.22:  Where can I get extra copies of this list?  What about back
  3135.         issues?
  3136.  
  3137. A:      For now, just pull it off the net; it is normally posted to
  3138.         comp.lang.c on the first of each month, with an Expiration: line
  3139.         which should keep it around all month.  It can also be found in
  3140.         the newsgroups comp.answers and news.answers .  Several sites
  3141.         archive news.answers postings and other FAQ lists, including
  3142.         this one: two sites are pit-manager.mit.edu (directory
  3143.         pub/usenet), and ftp.uu.net (directory usenet).  The archie
  3144.         server should help you find others.  See the meta-FAQ list in
  3145.         news.answers for more information; see also question 17.8.
  3146.  
  3147.         This list is an evolving document of questions which have been
  3148.         Frequent since before the Great Renaming, not just a collection
  3149.         of this month's interesting questions.  Older copies are
  3150.         obsolete and don't contain much, except the occasional typo,
  3151.         that the current list doesn't.
  3152.  
  3153.  
  3154. Bibliography
  3155.  
  3156. ANSI    American National Standard for Information Systems --
  3157.         Programming Language -- C, ANSI X3.159-1989 (see question 5.2).
  3158.  
  3159. JLB     Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall,
  3160.         1982, ISBN 0-13-970244-X.
  3161.  
  3162. H&S     Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  3163.         Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.
  3164.         (A third edition has recently been released.)
  3165.  
  3166. PCS     Mark R. Horton, Portable C Software, Prentice Hall, 1990,
  3167.         ISBN 0-13-868050-7.
  3168.  
  3169. EoPS    Brian W. Kernighan and P.J. Plauger, The Elements of Programming
  3170.         Style, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  3171.  
  3172. K&R I   Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3173.         Language, Prentice Hall, 1978, ISBN 0-13-110163-3.
  3174.  
  3175. K&R II  Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3176.         Language, Second Edition, Prentice Hall, 1988, ISBN 0-13-
  3177.         110362-8, 0-13-110370-9.
  3178.  
  3179. Knuth   Donald E. Knuth, The Art of Computer Programming, (3 vols.),
  3180.         Addison Wesley, 1981.
  3181.  
  3182. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989,
  3183.         ISBN 0-201-17928-8.
  3184.  
  3185.         P.J. Plauger, The Standard C Library, Prentice Hall, 1992,
  3186.         ISBN 0-13-131509-9.
  3187.  
  3188.         Harry Rabinowitz and Chaim Schaap, Portable C, Prentice-Hall,
  3189.         1990, ISBN 0-13-685967-4.
  3190.  
  3191. There is a more extensive bibliography in the revised Indian Hill style
  3192. guide (see question 14.3).  See also question 17.21.
  3193.  
  3194.  
  3195. Acknowledgements
  3196.  
  3197. Thanks to Jamshid Afshar, Sudheer Apte, Randall Atkinson, Dan Bernstein,
  3198. Vincent Broman, Stan Brown, Joe Buehler, Gordon Burditt, Burkhard Burow,
  3199. D'Arcy J.M. Cain, Raymond Chen, Christopher Calabrese, Paul Carter,
  3200. James Davies, Jutta Degener, Norm Diamond, Ray Dunn, Stephen M. Dunn,
  3201. Bjorn Engsig, Alexander Forst, Jeff Francis, Dave Gillespie, Samuel
  3202. Goldstein, Alasdair Grant, Ron Guilmette, Doug Gwyn, Tony Hansen, Joe
  3203. Harrington, Guy Harris, Jos Horsmeier, Blair Houghton, Kirk Johnson,
  3204. Peter Klausler, Andrew Koenig, Tom Koenig, John Lauro, Felix Lee, Don
  3205. Libes, Christopher Lott, Tim McDaniel, John R. MacMillan, Evan Manning,
  3206. Barry Margolin, Brad Mears, Mark Moraes, Darren Morby, Landon Curt Noll,
  3207. David O'Brien, Richard A. O'Keefe, Hans Olsson, Francois Pinard, Pat
  3208. Rankin, Erkki Ruohtula, Rich Salz, Chip Salzenberg, Paul Sand, Doug
  3209. Schmidt, Patricia Shanahan, Peter da Silva, Joshua Simons, Henry
  3210. Spencer, David Spuler, Erik Talvola, Clarke Thatcher, Wayne Throop,
  3211. Chris Torek, Goran Uddeborg, Wietse Venema, Ed Vielmetti, Larry Virden,
  3212. Chris Volpe, Freek Wiedijk, Dave Wolverton, Mitch Wright, Conway Yee,
  3213. and Zhuo Zang, who have contributed, directly or indirectly, to this
  3214. article.  Special thanks to Karl Heuer, and particularly to Mark Brader,
  3215. who (to borrow a line from Steve Johnson) have goaded me beyond my
  3216. inclination, and occasionally beyond my endurance, in relentless pursuit
  3217. of a better FAQ list.
  3218.  
  3219.                                         Steve Summit
  3220.                                         scs@adam.mit.edu
  3221.                                         scs%adam.mit.edu@mit.edu
  3222.                                         mit-eddie!adam.mit.edu!scs
  3223.  
  3224. This article is Copyright 1988, 1990-1993 by Steve Summit.
  3225. It may be freely redistributed so long as the author's name, and this
  3226. notice, are retained.
  3227. The C code in this article (vstrcat(), error(), etc.) is public domain
  3228. and may be used without restriction.
  3229.  
  3230.  
  3231.